路由在 Symfony 3.4 中不起作用

2023-11-27

我使用以下命令创建了一个新的 Symfony 3.4 项目:

composer create-project symfony/skeleton my-project

之后我添加了以下组件:

composer require twig
composer require annotations
composer require maker

并创建了一个控制器:

php bin/console make:controller

我添加了一个路线为“合法”的操作。这是默认控制器:

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function index()
    {
        return $this->render('index.html.twig', [
            'controller_name' => 'DefaultController',
        ]);
    }

    /**
     * @Route("/legal", name="legal")
     */
    public function legal()
    {
        return $this->render('legal.html.twig', []);
    }
}

文件config/routes.yaml:

#index:
#    path: /
#    defaults: { _controller: 'App\Controller\DefaultController::index' }

和 config/routes/annotations.yaml:

controllers:
    resource: ../../src/Controller/
    type: annotation

当我访问主页时,没有问题,页面正在显示。但是当我尝试 /legal 页面时,我遇到了 404 :

未找到 - 在此服务器上未找到请求的 URL /legal。

php bin/console debug:router显示预期:

 ------------------ -------- -------- ------ -------------------------- 
  Name               Method   Scheme   Host   Path                      
 ------------------ -------- -------- ------ -------------------------- 
  homepage           ANY      ANY      ANY    /                         
  legal              ANY      ANY      ANY    /legal                    
  _twig_error_test   ANY      ANY      ANY    /_error/{code}.{_format}  
 ------------------ -------- -------- ------ -------------------------- 

我使用控制台命令并删除 var/cache 目录的内容来清除缓存。但还是404。

我是 3.4 的新手。有任何想法吗 ?谢谢...


好吧,正如@Basel Issmail 指出的那样,交响乐/Flex不创建一个.htaccess就像以前的 Symfony 安装程序一样,但我已经忘记了。

我只有一个最小的 Apache 配置文件:

<VirtualHost *:80>
    DocumentRoot /path/to/my-project/public
    ServerName myproject.localhost

    <Directory /path/to/my-project/public>
        Options -Indexes +FollowSymLinks -MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

所以我创建了.htaccess文件输入/public/(其中index.php文件谎言),所需的最低配置如下:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

缺少的部分是将所有查询(除了资产等现有文件)重写为index.php,让 Symfony 处理路由。

- - 编辑 - -

您也可以使用 symfony flex 配方,而不是手动创建 .htaccess:

composer require apache-pack

这将安装这个 .htaccess 文件.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

路由在 Symfony 3.4 中不起作用 的相关文章

随机推荐