大网数据广告活动
服务器运维问答

Are multiple server blocks or one server block with redirects preferable in NGINX? Why?

· 52CE 我爱测

I want to use an NGINX configuration to redirect non-www to www and http to https. I have seen two methods to do this. One uses multiple server blocks, two of which redirect to the third, like so: server { listen 80; #listen for …

问题原文

原帖链接 · YPCrumble · CC BY-SA 3.0

I want to use an NGINX configuration to redirect non-www to www and http to https. I have seen two methods to do this. One uses multiple server blocks, two of which redirect to the third, like so:

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.
}

The second option is to have ONE server block listening to 80 and 443, and use an if statement within that block, like this:

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;
    }
    ...
}

Is one of these methods the best practice in NGINX? If so, why?

已采纳解答

原帖链接 · Tim · CC BY-SA 3.0

You should use multiple server blocks, and within each server use locations rather than if statements. It's more efficient and the behavior is more predictable.

Nginx article "if is evil" is a necessary read. You should also read "common pitfalls"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-01-02)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。