apache .htaccess 重写不应包括 www

apache .htaccess rewrite should not include www

我们有一个域 test.com,我们想要重定向 http://www.test.com to http://test.com and https://www.test.com to https://test.com,我们可以通过下面提到的规则实现相同的目的,但我们不需要 http://,除此之外我们还必须做什么为 https://

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

如果您希望所有内容都转到 https,则需要将规则更改为:

 RewriteEngine On
 RewriteBase /
 RewriteCond %{HTTPS} off [OR]
 RewriteCond %{HTTP_HOST} ^www\.test\.com$ [NC]
 RewriteRule ^(.*)$ https://test.com/ [R=301,L]

否则,您将需要针对 http 和 https 的单独规则:

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

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

您可以使用一个规则来处理 httphttps 流量:

RewriteEngine On
RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^ http%2://%1%{REQUEST_URI} [R=302,L,NE]