我想使用 NGINX 配置将非 www 重定向到 www,将 http 重定向到 https。我见过两种方法可以做到这一点。一种方法使用多个服务器块,其中两个重定向到第三个,如下所示:
server {
listen 80; #listen for all the HTTP requests
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate ssl.crt; #you have to put here...
ssl_certificate_key ssl.key; # ...paths to your certificate files
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate ssl.crt;
ssl_certificate_key ssl.key;
# Omitting rest of configuration for brevity.
}
第二种选择是让一个服务器块监听 80 和 443,并在该块中使用 if 语句,如下所示:
server {
listen 80;
listen [::]:80;
listen 443 ssl http2;
listen [::]:80 ipv6only=on;
listen [::]:443 ssl http2 ipv6only=on;
server_name example.com www.example.com;
if ($host ~* ^www\.(.*)) {
return 301 https://$1$request_uri;
}
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
...
}
这些方法之一是 NGINX 中的最佳实践吗?如果是,为什么?