301 重定向 URL 也被重写

301 redirect URLs that are also being rewritten

我正在使用 Slim 构建网站,建议使用以下 .htaccess 代码来创建漂亮的 URLs:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

这意味着像 http://example.com/account/login 这样的 URL 将 别名 用于 http://example.com/index.php/account/login,然后由我的前端控制器处理。到目前为止一切顺利。

但是,如果有人明确导航到

http://example.com/index.php/account/login

我希望它先重定向到:

http://example.com/account/login

然后

的别名

http://example.com/index.php/account/login

这样,用户将在他们的导航栏中看到 http://example.com/account/login

如何在 .htaccess 中同时处理这两个规则,最重要的是,在 .htaccess 中不对主机和域 (http://example.com) 进行硬编码?

这在子目录中也应该有效,例如:

http://example.com/site1/index.php/account/login -> http://example.com/site1/account/login

.htaccess 文件位于相对于文档根目录的 site1 目录中,而无需明确地将 site1 放入 .htaccess 中。

试试这个:

RewriteRule ^index\.php/(.*)$ / [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

在此规则之前您需要一个新的重定向规则:

RewriteEngine On

RewriteCond [=10=]#%{REQUEST_URI} ^([^#]*)#(.*)$
RewriteRule ^.*$ - [E=BASE:%2]

RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^index\.php(?:/(.*))?$ %{ENV:BASE} [L,R=302,NC,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]