【问题标题】:.htaccess redirect addin trailing slash.htaccess 重定向插件尾部斜杠
【发布时间】:2018-08-01 09:37:46
【问题描述】:

一段时间以来,我一直在使用以下 .htaccess 将非 https 重定向到 https:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

然而,本周一位 SEO 专家告诉我,这为这样的链接提供了 2 个重定向:

www.example.com/test

第一个 http s ://www.example.com/test 第二个到 http s ://www.example.com/test /

显然这对 SEO 不利,所以我尝试在最后一行添加 /,这不适用于文件,例如

www.example.com/test.php => https://www.example.com/test.php/

我进行了一些搜索,但似乎无法找到解决这两个问题的方法。谁能指出我正确的方向?

【问题讨论】:

    标签: .htaccess mod-rewrite seo


    【解决方案1】:

    如何在规则中添加对目录的检查(一个用于目录,一个用于文件):

    <IfModule mod_rewrite.c>
    RewriteEngine on
    
    # for directories without trailing slashes
    RewriteCond %{HTTPS} !=on [NC]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_URI} [^/]$
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]
    
    # for everything else
    RewriteCond %{HTTPS} !=on [NC]
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </IfModule>
    

    但是,这很有可能不起作用,因为从 /test/test/ 的重定向不是通过 Rewrite 发生的,而是通过 mod_dir 的 DirectorySlash 指令发生的。如果您真的只想进行这个重定向(我认为影响没有那么严重),那么您可以关闭 DirectorySlash 并通过 mod_rewrite 进行重定向:

    DirectorySlash Off
    
    <IfModule mod_rewrite.c>
    RewriteEngine on
    
    # for directories without trailing slashes
    RewriteCond %{HTTPS} !=on [NC]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_URI} [^/]$
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]
    
    # for everything else
    RewriteCond %{HTTPS} !=on [NC]
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    # Add trailing slashes for directories that have them missing
    RewriteCond %{HTTPS} on [NC]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{REQUEST_URI} [^/]$
    RewriteRule ^(.*)$ %{REQUEST_URI}/ [R=301,L]
    </IfModule>
    

    【讨论】:

    • 奇怪,这似乎在我的测试域上完美运行,但不适用于必须应用它的域。我也会让 SEO 专家来看看。感谢您的快速回复。
    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2021-05-21
    • 2019-03-28
    • 2017-09-28
    相关资源
    最近更新 更多