通用htaccess将www重定向到非www

遇到的问题:

我想将www.example.com重定向到example.com 。 以下htaccess代码可实现此目的:

RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以以通用的方式而不用对域名进行硬编码?

解决方案:

解决方案一

 RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 

与迈克尔的相同,除了这一作品:P

解决方案二

但是,如果我们需要对单独的http和https执行此操作:

 RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L] 

解决方案三

将非www重定向到www (均为:http + https)

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

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L] 

原文链接: http://findmybug.cn/article/generic-htaccess-redirect-www-to-non-www

发布了0 篇原创文章 · 获赞 0 · 访问量 33

猜你喜欢

转载自blog.csdn.net/eyeotec/article/details/103988093
www