在根域上强制使用 HTTPS 和 www,但在子域上不强制
Forcing HTTPS and www on root domain, but not on subdomains
我想在整个站点强制使用 HTTPS,这已经完成,没有问题:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC,NE]
但我还想确保发送到顶级域的请求被重定向到 www.example.com
我找到了 this answer,但似乎这也会将子域重定向到 www? ...或者可能不会,因为子域不使用自己的 .htaccess
?
除了上述之外,我还尝试了下面的 www.
部分,但它似乎不起作用?
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)|webp$ [NC]
RewriteRule ^ https://www.example.com/%{REQUEST_URI} [R=301,L,NC,NE]
我认为如果它不以 example.com
开头就会失败,因此将单独保留任何子域,包括 www?
但是好像根本没有触发。
此配置应该可以满足您的需求:
RewriteEngine On
# When on the root domain (with HTTPs; on "www" or the root domain only):
# Redirect to WWW Root
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^(?!www\.)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]
# When HTTP is off (on "www" or the root domain only)
# Redirect to the HTTPs Version of the WWW root
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(?:www\.|)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]
您还可以使用 this website 测试您的配置。
我想在整个站点强制使用 HTTPS,这已经完成,没有问题:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC,NE]
但我还想确保发送到顶级域的请求被重定向到 www.example.com
我找到了 this answer,但似乎这也会将子域重定向到 www? ...或者可能不会,因为子域不使用自己的 .htaccess
?
除了上述之外,我还尝试了下面的 www.
部分,但它似乎不起作用?
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)|webp$ [NC]
RewriteRule ^ https://www.example.com/%{REQUEST_URI} [R=301,L,NC,NE]
我认为如果它不以 example.com
开头就会失败,因此将单独保留任何子域,包括 www?
但是好像根本没有触发。
此配置应该可以满足您的需求:
RewriteEngine On
# When on the root domain (with HTTPs; on "www" or the root domain only):
# Redirect to WWW Root
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^(?!www\.)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]
# When HTTP is off (on "www" or the root domain only)
# Redirect to the HTTPs Version of the WWW root
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(?:www\.|)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]
您还可以使用 this website 测试您的配置。