.htaccess配置问题:重定向后URL自动添加index.php
我需要将所有请求重定向到domain.tld/shop/...路径,但实际重定向后的URL总会自动添加index.php,变成domain.tld/shop/index.php/...。我已在.htaccess文件开头添加了如下规则:
<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_URI} !^/shop RewriteRule ^(.*)$ /shop/$1 [L,R=301] </IfModule>
完整的.htaccess文件内容如下:
<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_URI} !^/shop RewriteRule ^(.*)$ /shop/$1 [L,R=301] </IfModule> # BEGIN Shopware # The directives (lines) between "# BEGIN Shopware" and "# END Shopware" are dynamically generated. Any changes to the directives between these markers will be overwritten. DirectoryIndex index.php <IfModule mod_negotiation.c> Options -MultiViews </IfModule> <IfModule mod_rewrite.c> RewriteEngine On 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}] RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [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}/index.php [L] </IfModule> <IfModule !mod_rewrite.c> <IfModule mod_alias.c> RedirectMatch 302 ^/$ /index.php/ </IfModule> </IfModule> <IfModule mod_headers.c> <FilesMatch "\.(?i:svg)$"> Header set Content-Security-Policy "script-src 'none'" </FilesMatch> </IfModule> # END Shopware
注:我也尝试过使用如下条件:
RewriteCond %{REQUEST_URI} !^/shop/
并且将规则放在文件的不同位置,但都没有效果。
问题根源在于Shopware自动生成的重写规则与你的自定义重定向规则冲突,特别是RewriteRule ^ %{ENV:BASE}/index.php [L]会将所有非文件请求强制转发到index.php,叠加你的重定向后就出现了多余的index.php路径。
按以下步骤修改:
优化自定义重定向规则
调整初始重定向规则,避免循环并精准匹配非shop路径的请求:<IfModule mod_rewrite.c> RewriteEngine On # 排除shop路径、实际存在的文件和目录 RewriteCond %{REQUEST_URI} !^/shop/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /shop/$1 [L,R=302] </IfModule>先使用
R=302临时重定向测试,确认正常后再改为R=301永久重定向,避免浏览器缓存旧规则修正Shopware的BASE环境变量
Shopware通过BASE变量构建重写路径,需要确保它指向/shop而非根目录。将Shopware区块内的BASE设置规则替换为:RewriteRule ^ - [E=BASE:/shop]注意:Shopware自动生成区块可能会覆盖手动修改,建议优先通过Shopware后台设置调整站点基础路径
移除index.php的重定向规则
修改Shopware中处理index.php的重定向规则,确保它只针对shop路径下的index.php:RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^shop/index\.php(?:/(.*)|$) /shop/$1 [R=302,L]这条规则会将
/shop/index.php/xxx重定向为/shop/xxx,自动移除多余的index.php。确认DirectoryIndex配置
确保shop目录的默认索引文件设置正确,可在根目录.htaccess中补充:<Directory "/shop"> DirectoryIndex index.php </Directory>
内容的提问来源于stack exchange,提问作者Ezycod

