19

This is my nginx configuration (running as docker container, in case it matters):

events {
    worker_connections 4096;  ## Default: 1024
}

http {
    server {
        server_name registry.mydomain;
        listen 80;
        listen 443 ssl;
        client_max_body_size 0;  # Disables checking, to avoid "request entity too large"
        ssl_certificate /etc/nginx/certs/registry.crt;
        ssl_certificate_key /etc/nginx/certs/registry.key;

        location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://registry:5000;
        }
    }
}

The problem that I have is that nginx is serving that site even for requests to other domains. This is expected:

$ http http://registry.mydomain/v2/_catalog?n=100
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 20
Content-Type: application/json; charset=utf-8
Date: Thu, 05 Apr 2018 12:43:21 GMT
Docker-Distribution-Api-Version: registry/2.0
Server: nginx/1.13.11
X-Content-Type-Options: nosniff

{
    "repositories": []
}

But this is not expected:

$ http http://localhost/v2/_catalog?n=100
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 20
Content-Type: application/json; charset=utf-8
Date: Thu, 05 Apr 2018 12:39:57 GMT
Docker-Distribution-Api-Version: registry/2.0
Server: nginx/1.13.11
X-Content-Type-Options: nosniff

{
    "repositories": []
}

Why is that? How can I tell nginx to not serve requests to undefined servers?

1 Answer 1

20

nginx always has a default server. In the absence of any server block explicitly marked as default_server, nginx will use the first server with a matching listen directive.

You can define a catch-all server block to handle any host names that do not match your server_name value.

For example:

server {
    listen 80 default_server;
    listen 443 ssl default_server;

    ssl_certificate     /path/to/some/other/cert.pem;
    ssl_certificate_key /path/to/some/other/key.pem;

    return 444;
}

Of course, browsers connecting over https will always complain about the certificate before nginx can process the request.

See this document for more.

3
  • nginx fails to start: nginx: [emerg] no "ssl_certificate" is defined for the "listen ... ssl" directive Commented Jun 9, 2022 at 1:03
  • @EvgeniyBerezovsky Copy the ssl_certificate and ssl_certificate_key statements, from one of your other server blocks into this new server block. (answer updated) Commented Jun 9, 2022 at 6:31
  • Thanks for adding it to your answer. Commented Jun 9, 2022 at 6:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .