首页 > 解决方案 > 搜索引擎友好的 URL - .htaccess

问题描述

在我的主机的根文件夹中,我有一个 htaccess 文件,其中包含以下重定向到 https 和 www 的代码:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

在 /news/ 文件夹中,我有 entry.php 文件,例如 ?slug=this-is-first-entry。我希望它看起来像这样https://www.example.com/news/this-is-first-entry

所以我想把这个重定向https://www.example.com/news/entry.php?slug=this-is-first-entry到这个https://www.example.com/news/this-is-first-entry

我在 /news/ 文件夹中的 .htaccess 中有此代码:

RewriteRule ^([^/\.]+)$ entry.php?slug=$1 [NC,L]

它工作正常,但从根文件夹重定向 https 和 www 不起作用。请帮忙,我不熟悉htaccess。

标签: .htaccessurlmod-rewriteurl-rewritingfriendly-url

解决方案


这是一个拇指规则。如果当前目录有一个 .htaccess ,RewriteEngine ON那么它会覆盖父级 .htaccess 指令。如果您希望在此之前应用父 .htaccess 规则,请使用以下选项:

RewriteOptions InheritBefore

行前RewriteEngine On

因此 /news/ 文件夹中的 htaccess 文件将变为:

RewriteOptions InheritBefore
RewriteEngine ON
RewriteRule ^([^/\.]+)$ entry.php?slug=$1 [NC,L]

附加建议:如果您尝试重写不存在的文件和目录,如果是这种情况,则将 htaccess 放在您的新闻文件夹中,如下所示。

RewriteOptions InheritBefore
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)$ entry.php?slug=$1 [NC,L]

推荐阅读