【问题标题】:CakePHP - Routing problems on external links and webrootCakePHP - 外部链接和 webroot 上的路由问题
【发布时间】:2018-03-13 02:53:32
【问题描述】:

我像这样为我的网站自定义了基本路径:

Router::scope('/', function (RouteBuilder $routes) {
    //$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    //My custom base path
    $routes->connect('/', ['controller' => 'Posts', 'action' => 'index', 'home']);

    //Connect the rest of PagesController URLs
    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    //I don't quite understand what this line does
    $routes->fallbacks(DashedRoute::class);
});

然后,当我像这样在控制器内部重定向时,URL 是正确的:

return $this->redirect(['controller' => 'Posts', 'action' => 'view', $data['post_id']]);

//output:
// localhost/jayblog/posts/view/2

但是对于外部链接和WWWROOT,它会返回错误的链接:

<li><a href="https://www.example.com" target="_blank" title="Twitter">LINK</a></li>

//output is wrong:
// localhost/jayblog/https://www.example.com

<?= $this->Html->image(WWW_ROOT.DS.'files'.DS.$photos[$i]->file_name); ?>

//output:
// jayblogD:\path\to\file.PNG

请任何人建议我如何解决此问题。谢谢!

【问题讨论】:

    标签: cakephp routing routes cakephp-3.0 wwwroot


    【解决方案1】:

    因为 WWW_ROOT 是绝对文件系统路径,而不是 HTML::image 所期望的相对路径。这永远行不通:

    <?= $this->Html->image(WWW_ROOT.DS.'files'.DS.$photos[$i]->file_name); ?>
    

    调试你的变量,看看发生了什么,例如

    var_dump(WWW_ROOT);
    

    请查看 Html::image() 文档 https://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-images 并将其传递给文档请求之类的数组,或者在您的情况下更可能是这样的:

    <?= $this->Html->image('/photos-directory/'.$photos[$i]->file_name); ?>
    

    照片目录可能存在于 /var/www/your-project/photos-directory 之类的位置

    【讨论】:

    • 哦,我知道我现在用image 助手做错了什么,谢谢!你知道外链有什么问题吗?
    【解决方案2】:

    试试下面这个替换

    $routes->fallbacks(DashedRoute::class); to $routes->fallbacks('InflectedRoute');
    
    <?php
    use Cake\Core\Plugin;
    use Cake\Routing\Router;
    
    Router::defaultRouteClass('Route');
    
    Router::scope('/', function ($routes) {
    
        $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
        $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
    
    
        $routes->fallbacks('InflectedRoute');
    });
    
    Router::extensions('json', 'xml');
    /**
     * Load all plugin routes.  See the Plugin documentation on
     * how to customize the loading of plugin routes.
     */
    Plugin::routes();
    ?>
    

    它对我有用。

    <ul>
    <li><a href="http://www.cakephp.org/" target="_blank">
               <?php echo $this->Html->image('technology-use/cakephp.jpg', array('alt' => 'images'));?></a></li>
    </ul>
    

    【讨论】:

    • 看起来您的基本路径没有被修改,所以没有任何异常行为。我尝试了路由扩展,但没有帮助。
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 2022-01-17
    • 2012-09-12
    • 1970-01-01
    • 2012-03-03
    • 2012-11-28
    • 1970-01-01
    相关资源
    最近更新 更多