我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
当前回答
重定向非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]
其他回答
完整的通用WWW处理程序,http/https
我没有看到一个完整的答案。我用这个来处理WWW的包含。
通用的。不需要域信息。 强制WWW主域:www.domain.com 删除子域名sub.domain.com上的WWW 保持HTTP/HTTPS状态。 允许域/子域单独的cookie
请让我知道这是如何工作的,或者如果我留下了漏洞。
RewriteEngine On
RewriteBase /
# Force WWW. when no subdomain in host
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ [NC]
RewriteCond %{HTTPS}s ^on(s)|off [NC]
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Remove WWW. when subdomain(s) in host
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|off [NC]
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)(.+\.)(.+\.)(.+)$ [NC]
RewriteRule ^ %1%3%4%5%{REQUEST_URI} [R=301,L]
以下是将一个www URL重定向到no-www的规则:
#########################
# redirect www to no-www
#########################
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]
以下是将一个no-www URL重定向到www的规则:
#########################
# redirect no-www to www
#########################
RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]
注意,我使用了NE标志来防止apache转义查询字符串。如果没有这个标志,apache将把请求的URL http://www.example.com/?foo%20bar更改为http://www.example.com/?foo%2250bar
但是如果我们需要为单独的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]
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
和迈克尔的一样,除了这个有用:P
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]
RewriteCond捕获www后HTTP_HOST变量中的所有内容。并将其保存在%1中。
RewriteRule捕获了没有/开头的URL,并将其保存在$1中。