我希望所有不带 www 的流量(包括 https)都重定向到带有 www 的相应 url。
所以http://example.com->http://www.example.com,https://example.com->https://www.example.com
网上有很多关于强制使用 SSL 的信息,我不想这样做,也不想强制使用 www,但只适用于 http。只需添加一个 s 并将 listen 80 更改为 listen 443 即可破坏 http 站点。这是我目前的配置:
server {
listen 80;
server_name example.com;
location / {
rewrite ^/(.*)$ http://www.example.com/$1 permanent;
}
}
server {
listen 80;
server_name www.example.com;
root /opt/example;
index index.html;
<locations stuff>
}
server {
listen 443;
server_name example.com;
ssl on;
ssl_certificate /opt/nginx/ssl/server.crt;
ssl_certificate_key /opt/nginx/ssl/server.key;
location / {
rewrite ^/(.*)$ https://www.example.com/$1 permanent;
}
}
server {
listen 443;
server_name www.example.com;
root /opt/example;
ssl on;
ssl_certificate /opt/nginx/ssl/server.crt;
ssl_certificate_key /opt/nginx/ssl/server.key;
<locations stuff>
}
答案1
这是我自己配置的精简版,我认为它可以满足您的要求:
server {
listen 80 default;
listen 443 default ssl;
server_name *.example.com;
if ($host = example.com) {
rewrite ^(.*) $scheme://www.example.com$1 permanent;
}
root /opt/example;
ssl on;
ssl_certificate /opt/nginx/ssl/server.crt;
ssl_certificate_key /opt/nginx/ssl/server.key;
}