在 NGINX 中,是多个服务器块还是一个带有重定向的服务器块?为什么?

YPC*_*ble 4 nginx

我想使用 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 中的最佳实践吗?如果是这样,为什么?

Tim*_*Tim 6

您应该使用多个服务器块,并在每个服务器内使用位置而不是 if 语句。它更有效,行为更可预测。

Nginx 文章“如果是邪恶的”是必读的。您还应该阅读“常见陷阱