【问题标题】:Seo friendly URL - .htaccess搜索引擎友好的 URL - .htaccess
【发布时间】:2021-06-12 14:35:28
【问题描述】:

在我主机​​的根文件夹中,我有一个 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。

【问题讨论】:

    标签: .htaccess url mod-rewrite url-rewriting friendly-url


    【解决方案1】:

    这是一条拇指规则。如果当前目录有一个带有RewriteEngine ON 的 .htaccess,那么它会覆盖父级 .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]
    

    【讨论】:

    • 为什么要多加两行? RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d。它们是什么意思?
    • @test,如果页面(uri 的部分)不存在则检查条件,然后仅通过 entry.php 提供它,否则它甚至会为现有页面(如 js、css 等)提供条目。 php 文件。
    • 非常感谢。我还有一个问题。在https://www.example.com/news/ 上,我使用查询字符串?category=test 对条目进行排序是否可以使用.htaccess 使其更好,例如https://www.example.com/news/category/test 或https://www.example.com/news/test。虽然我认为第二个会更糟,因为它会导致与查询字符串 slug 混淆。
    猜你喜欢
    • 2012-06-18
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2013-10-16
    • 2014-04-26
    • 2014-11-09
    相关资源
    最近更新 更多