从网址中删除'index.html'并在一个301重定向中添加'www'

Mar*_*aio 3 apache .htaccess mod-rewrite redirect url-rewriting

为了删除index.html或删除index.htm网址,我在我的网站中使用以下内容.htaccess

RewriteCond %{REQUEST_URI} /index\.html?$ [NC]
RewriteRule ^(.*)index\.html?$ "/$1" [NC,R=301,NE,L]
Run Code Online (Sandbox Code Playgroud)

这有效!(有关此问题末尾的标志的更多信息*)

然后为了添加www网址,我在我的网站中使用以下内容.htaccess

RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.mydomain.com/$1" [R=301,NE,L]
Run Code Online (Sandbox Code Playgroud)

这也有效!

这里的问题是如何在以下情况下避免上述规则创建的双重定向:

  1. 浏览器要求 http://mydomain.com/path/index.html
  2. 服务器将301标头发送到redircet浏览器http://mydomain.com/path/
  3. 浏览器请求 http://mydomain.com/path/
  4. 现在服务器将301标头发送到redircet浏览器http://www.mydomain.com/path/

这显然不是很聪明,因为要求的用户http://mydomain.com/path/index.html会被双重定向,他觉得页面太慢了.此外,Googlebot可能会停止跟踪链接原因导致双重redircetion(我不确定最后一个,我不想讨论这个,这只是另一个可能的问题.)

谢谢!


*可能感兴趣的人:

  • NC用于重定向大写文件即INDEX.HTML/ InDeX.HtM
  • NE用于避免双url编码我避免 http://.../index.html?hello=ba%20be 被重定向到 http://.../index.html?hello=ba%2520be
  • QSA用来重定向还查询,即 http://.../index.html?hello=babehttp://.../?hello=babe(不需要感谢anubhava答案)

anu*_*ava 6

为避免双重定向,.htaccess文件中的另一个规则符合以下两个条件:

Options +FollowSymlinks -MultiViews
RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . http://www.%{HTTP_HOST}%1 [R=301,NE,L]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule . http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . %1 [R=301,NE,L]
Run Code Online (Sandbox Code Playgroud)

因此,如果输入URL是http://mydomain.com/path/index.html这两个条件在这里的第一个规则中得到满足,那么将有1个单一重定向(301)http://www.mydomain.com/path/.

另外我认为QSA上面并不真正需要标志,因为你不是在操纵查询字符串.