我想使用 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.
}
Run Code Online (Sandbox Code Playgroud)
第二个选项是让一个服务器块侦听 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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
这些方法之一是 NGINX 中的最佳实践吗?如果是这样,为什么?
归档时间: |
|
查看次数: |
436 次 |
最近记录: |