Nginx seems to ignore server_name when ssl and htt

2019-07-27 02:04发布

问题:

I have this nginx configuration:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name www.example.com;
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl http2;
    server_name www.example.com;
    include snippets/ssl-params.conf;
    client_max_body_size 5G;
                location / {
                        proxy_pass http://127.0.0.1:8888;
                }
}

So http://www.example.com is redirected to https://www.example.com. Problem is, that https://example.com also works and serves proxy pass to port 8888. How can I prevent it to work? I need just version with www to be working. Parameter server_name does not seem to have any effect. I am using "nginx version: nginx/1.10.1".

回答1:

Unless you explicitly define a default server for port 443, nginx will use the first matching server block to process the request. See this document for details.

The solution is to explicitly define a default server with the desired behaviour, for example:

server {
    listen 443 ssl http2 default_server;
    return 301 https://www.example.com$request_uri;
    include snippets/ssl-params.conf;
}    

In fact, you could probably roll it into your port 80 server block, if you delete the server_name directive:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl http2 default_server;
    return 301 https://www.example.com$request_uri;
    include snippets/ssl-params.conf;
}

server {
    listen 443 ssl http2;
    server_name www.example.com;
    include snippets/ssl-params.conf;
    client_max_body_size 5G;
    location / {
        proxy_pass http://127.0.0.1:8888;
    }
}


标签: ssl nginx