Symfony 从路由中删除前三个字符

Posted

技术标签:

【中文标题】Symfony 从路由中删除前三个字符【英文标题】:Symfony remove first three characters from route 【发布时间】:2016-11-01 20:41:55 【问题描述】:

我有一个简单的 Symfony 2.8 应用程序。在本地主机上它工作正常。但是当我将它上传到共享主机时,只有“/”路由有效。但在每条 >= 4 个字符长的路线中,前三个字符消失了。

例如:

I go to domain.com/123456 and Symfony says No route found for "GET 465"
I go to domain.com/admin and Symfony says No route found for "GET in"
I go to domain.com/blog and Symfony says No route found for "GET g"
...

当我使用 .htaccess 将所有对 web 目录的直接访问重定向到根目录时,它甚至在 localhost 上也发生了。我有来自here 的.htaccess 解决方案。

/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %REQUEST_FILENAME !-f
    RewriteRule ^(.*)$ web/$1 [QSA,L]
</IfModule>

/web/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %THE_REQUEST ^(GET|HEAD)\ /web/
        RewriteRule ^(.*)$ /$1 [L,R=301]
    RewriteCond %REQUEST_FILENAME !-f
    RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>

路由器:调试输出

 -------------------------- ---------- -------- ------ ----------------------------------- 
  Name                       Method     Scheme   Host   Path                               
 -------------------------- ---------- -------- ------ ----------------------------------- 
  _wdt                       ANY        ANY      ANY    /_wdt/token                      
  _profiler_home             ANY        ANY      ANY    /_profiler/                        
  _profiler_search           ANY        ANY      ANY    /_profiler/search                  
  _profiler_search_bar       ANY        ANY      ANY    /_profiler/search_bar              
  _profiler_purge            ANY        ANY      ANY    /_profiler/purge                   
  _profiler_info             ANY        ANY      ANY    /_profiler/info/about            
  _profiler_phpinfo          ANY        ANY      ANY    /_profiler/phpinfo                 
  _profiler_search_results   ANY        ANY      ANY    /_profiler/token/search/results  
  _profiler                  ANY        ANY      ANY    /_profiler/token                 
  _profiler_router           ANY        ANY      ANY    /_profiler/token/router          
  _profiler_exception        ANY        ANY      ANY    /_profiler/token/exception       
  _profiler_exception_css    ANY        ANY      ANY    /_profiler/token/exception.css   
  _twig_error_test           ANY        ANY      ANY    /_error/code._format           
  admin-index                ANY        ANY      ANY    /admin                             
  admin-settings             ANY        ANY      ANY    /admin/nastaveni                   
  admin-blog-index           GET        ANY      ANY    /admin/blog/                       
  admin-blog-new             GET|POST   ANY      ANY    /admin/blog/napsat-clanek          
  admin-blog-show            GET        ANY      ANY    /admin/blog/id                   
  admin-blog-edit            GET|POST   ANY      ANY    /admin/blog/id/upravit           
  admin-blog-delete          DELETE     ANY      ANY    /admin/blog/id                   
  blog-detail                ANY        ANY      ANY    /blog/clanek/id/articleSlug    
  blog-index                 ANY        ANY      ANY    /blog/tagSlug/currentPage      
  homepage                   ANY        ANY      ANY    /                                  
  about-us                   ANY        ANY      ANY    /o-projektu                        
  travelTimeline             ANY        ANY      ANY    /plan-cesty                        
 -------------------------- ---------- -------- ------ ----------------------------------- 

我有默认的 routing.yml 和 security.yml

你能看出错误吗?


---编辑---

新的 /.htaccess

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # Explicitly disable rewriting for front controllers
    RewriteRule ^/web/app_dev.php - [L]
    RewriteRule ^/web/app.php - [L]

    # Fix the bundles folder
    RewriteRule ^bundles/(.*)$ /web/bundles/$1  [QSA,L]

    RewriteCond %REQUEST_FILENAME !-f
    # Change below before deploying to production
    RewriteRule ^(.*)$ /web/app.php [QSA,L]
    #RewriteRule ^(.*)$ /web/app_dev.php [QSA,L]
</IfModule>

/web/.htaccess(来自 Symfony 的原创)

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php

# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks

# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %REQUEST_URI::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by apache
    RewriteCond %HTTP:Authorization .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%HTTP:Authorization]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %ENV:REDIRECT_STATUS ^$
    RewriteRule ^app\.php(/(.*)|$) %ENV:BASE/$2 [R=301,L]

    # 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/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

使用此配置和组件 paragonie/random_compact 1.4 版,我有时会收到错误,我可以通过页面刷新来处理它。

【问题讨论】:

你好,卡雷尔。你能分享 php app/console router:debug 的输出吗?那会有所帮助。谢谢 我已将其添加到第一篇文章中。 您的虚拟主机是如何配置的。 symfony 项目中 vhost 的根目录通常是 web 文件夹。 不幸的是,在我的共享主机上,我无法看到或使用 VirtualHost。 我尝试使用 Symfony 的原始 .htaccess,但出现错误“您的系统上没有安装合适的 CSPRNG”。我发现它是由 paragonie/random_compact 组件引起的,我应该使用 1.4 版。当我使用这个版本时,这个错误是固定的,但不是实际的问题。但是当我使用不同的 .htaccess 时,我有时会收到错误,页面刷新会修复它。但这对生产不利:)。 (第一篇文章中的新 .htaccess) 【参考方案1】:

我为你提供了这个替代方案,使用 vhost 和 symfony 默认的 .htaccess

<VirtualHost 192.168.0.1:80>
    ServerName mydomain.com

    DocumentRoot /var/www/myproject/web

    <Directory />
            Header set Access-Control-Allow-Origin "*"
            Options FollowSymLinks
            AllowOverride None
    </Directory>

    <Directory /var/www/myproject/web>
             Options Indexes FollowSymLinks MultiViews
             AllowOverride All
             Order allow,deny
             allow from all
    </Directory>

    ErrorLog $APACHE_LOG_DIR/error-myproject.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel notice

    CustomLog $APACHE_LOG_DIR/access-myproject.log combined

</VirtualHost>

还有web/.htaccess文件(有点长,网上没找到)

DirectoryIndex app.php

# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks

# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %REQUEST_URI::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by apache
    RewriteCond %HTTP:Authorization .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%HTTP:Authorization]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %ENV:REDIRECT_STATUS ^$
    RewriteRule ^app\.php(/(.*)|$) %ENV:BASE/$2 [R=301,L]

    # 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/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

【讨论】:

不幸的是,在我的共享主机上,我无法使用 VirtualHost。

以上是关于Symfony 从路由中删除前三个字符的主要内容,如果未能解决你的问题,请参考以下文章

使用 localhost 从主机访问 Vagrant 机器上的 symfony Web 服务器

删除捆绑包后的 symfony 致命错误

Symfony 2.3 Bad Credentials 自定义提供程序

Symfony 5:/lucky/number 应用程序的 404 页面

Symfony 5:如何从路由规则中获取选项数据

如何在 Symfony 路由中使用锚点?