
本文旨在帮助开发者解决在使用 Symfony 框架(特别是结合 EasyAdmin)时,遇到的子域名路由在本地开发环境正常,但部署到服务器上出现 404 错误的问题。文章将分析可能的原因,并提供详细的排查步骤和解决方案,包括服务器配置、路由设置以及 EasyAdmin 的相关配置。
当 Symfony 应用在本地开发环境(例如使用 symfony server:start)运行时,路由通常能正常工作。然而,当部署到生产服务器,并通过子域名访问时,可能会遇到 404 错误。这通常表示服务器无法找到与请求 URL 匹配的路由。可能的原因包括:
以下步骤将帮助您排查并解决子域名路由 404 错误:
确保服务器已正确配置以处理子域名请求。以下是 Apache 和 Nginx 的配置示例:
Apache 配置 (VirtualHost):
<VirtualHost *:80>
    ServerName subdomain.domain.com
    DocumentRoot /path/to/your/project/public
    <Directory /path/to/your/project/public>
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>Nginx 配置 (Server Block):
server {
    listen 80;
    server_name subdomain.domain.com;
    root /path/to/your/project/public;
    index index.php;
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 替换为你的 PHP-FPM socket
    }
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
}注意事项:
如果使用 Apache 服务器,请确保您的项目根目录和 public 目录下都存在 .htaccess 文件,并且配置正确。
项目根目录 .htaccess:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC]
    RewriteRule ^ %1 [L,NE,R=302]
    RewriteRule ^(.*)$ public/index.php?$1 [L,QSA]
</IfModule>public 目录 .htaccess:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?$1 [L,QSA]
</IfModule>注意事项:
使用 php bin/console debug:router 命令检查您的路由配置。确保您要访问的路由已正确定义,并且没有冲突。
例如,如果您的路由定义如下:
/**
 * @Route("/admin", name="admin")
 */
public function index(): Response
{
    // ...
}则 php bin/console debug:router 的输出应该包含类似以下的内容:
admin ANY ANY ANY /admin
如果路由未正确显示,请检查您的路由配置,并确保路由注解或 YAML/XML 配置文件中的路径正确无误。
如果您在使用 EasyAdmin,某些配置可能会影响路由。例如,URL 签名可能会导致问题。
禁用 URL 签名:
在 DashboardController 的 configureDashboard() 方法中,禁用 URL 签名:
public function configureDashboard(): Dashboard
{
    return Dashboard::new()
        ->disableUrlSignatures()
        // ...
}注意事项:
在修改了任何配置后,请清除 Symfony 缓存:
php bin/console cache:clear
确保 security.yaml 文件中没有阻止访问 /admin 路由的访问控制规则。 注释掉或删除任何可能阻止访问的规则。
access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN } # 确保此行被注释掉或删除解决 Symfony 子域名路由 404 错误需要仔细排查服务器配置、.htaccess 文件、Symfony 路由配置和 EasyAdmin 相关配置。通过遵循以上步骤,您应该能够找到并解决问题。记住,在进行任何更改后,都要清除缓存并重新启动服务器。
以上就是Symfony 子域名路由 404 错误排查与解决的详细内容,更多请关注php中文网其它相关文章!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号