问题原文
原帖链接 · Recap · CC BY-SA 3.0
How do you redirect all non-www links to my website to https://www. I know that there are a lot of solutions for .htaccess but I haven't been able to find anything sufficient for nginx.
At the moment all I have is
##
# Redirect non-www to www
##
server {
listen 80;
server_name example.com; # add other domains separated by a space as necessary
rewrite ^/(.*)$ https://www.example.com/$1 permanent;
}
which redirects:
example.com
www.example.com
http://example.com
http://www.example.com
to
https://www.example.com which is what I want, except that https://example.com doesn't redirect https://www.example.com
How do so how do I get https:// to redirect to https://www.?
已采纳解答
原帖链接 · Recap · CC BY-SA 3.0
Since my last answer using the "if" statement is not recommended in most cases, I came up with another solution which seems to be working perfectly.
What I did was create another server block with www in the server_name and had my other server blocks redirect to it.
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://www.example.com$request_uri;
}
# HTTPS — proxy all requests to the Node app
server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
return 301 https://www.example.com$request_uri;
# Use the Let’s Encrypt certificates
...
}
server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
# Use the Let’s Encrypt certificates
...
}
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
