.htaccess redirect addin trailing slash

时间:2018-02-21 17:33:36

标签: .htaccess mod-rewrite seo

我一直在使用以下.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 /

显然这对搜索引擎优化有害,所以我尝试在最后一行添加/,这对文件不起作用,例如

www.example.com/test.php =&gt; https://www.example.com/test.php/

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

1 个答案:

答案 0 :(得分:2)

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

<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/的重定向不是通过重写,而是通过mod_dir的DirectorySlash指令发生,因此很有可能无效。如果真的想要只重做一次(我不认为影响是那么严重),那么你可以关闭DirectorySlash并通过mod_rewrite进行重定向:< / p>

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>
相关问题