关于Stack Overflow的第二个问题!我们的目标是将我们网站的所有请求永久重定向到https://www.example.com
。我们目前使用以下代码将http://example.com
和http://www.example.com
重定向到https://www.example.com
,但是,在Stack Overflow花了很长时间寻找解决方案之后,我们还没有找到办法还要将https://example.com
重定向到https://www.example.com
。非常感谢你的帮助。
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
答案 0 :(得分:1)
最好在一条规则中处理这个问题:
RewriteEngine On
# add www and force https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=302,L,NE]
302
更改为301
。答案 1 :(得分:0)
为了补充@ anubhava优雅的Apache解决方案,我们最近在Nginx上找到了一种方法:
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 443;
server_name example.com;
return 301 https://www.example.com$request_uri;
}