将www重定向到非www,http重定向到https,将domain.com重定向到domain.com/index.php

时间:2017-10-03 12:51:27

标签: .htaccess redirect

我试图使用.htaccess重定向:

1)所有www到非www例如www.example.com/page.php到example.com/page.php

2)所有http到https,例如http://example.com/page.phphttps://example.com/page.php

3)域名(和子文件夹)到他们的index.php页面,例如https://example.comhttps://example.com/index.phphttps://example.com/en-gb/https://example.com/en-gb/index.php

我可以得到1)和2)正确使用:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI} 

但我也在努力包括3)。我试过这个但没有运气:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI}

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php

更新 - 试过这个但没有运气

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI}

Redirect / https://example.com/index.php

第二次更新 - 尝试过此操作但与之前相同的是将index.php递归添加到URL:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI}

RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) https://example.com/index.php$1

2 个答案:

答案 0 :(得分:1)

清除浏览器缓存并将以下代码放在主目录.htaccess文件中,无需转到每个文件夹并将代码放在那里:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://yoursite.com/$1 [L,R=302]
# the two lines above will catch both http://www & http:// and force https:// 
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*) https://yoursite.com/$1 [L,R=302]
# the three lines above will catch only https://www and redirect it to none wwww 
RewriteCond %{REQUEST_URI}  ^/$ [NC]
RewriteRule  ^    /index.php [R=302,L,NE]
# the two lines above will force index.php to domain when request to index.php comes without it
RewriteCond %{REQUEST_FILENAME} -d  
RewriteRule  ^(.*)/$    /$1/index.php [R=302,L,NE]
# the two lines above will force index.php to any directory when request to index.php comes without it

测试它,如果它是oK,则将每302更改为301以获得永久重定向

答案 1 :(得分:0)

嗯 - 感谢大家的帮助:)。

我终于到了那里。如果这有助于其他人遇到同样的问题...这就在根目录中:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI}

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^$ https://example.com/index.php

这在每个文件夹中:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI}

RewriteCond %{REQUESTFILENAME} !-f
RewriteRule ^$ https://example.com/en-gb/index.php