1

The docs suggest that the following server block will drop all requests without a HTTP HOST header:

server {
    listen      80;
    server_name "";
    return      444;
}

This does seem to work:

curl -I http://example.com/ -H "Host:" -v --http1.0 --insecure

curl: (52) Empty reply from server

How would I apply this block to HTTPS requests? For example, the following triggers an alert from Django, so it seems to be getting past nginx:

curl -I https://example.com/ -H "Host:" -v --http1.0 --insecure

Invalid HTTP_HOST header: '/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035.

I've tried to implement this solution, but still get the same results:

if ($host !~* ^(example.com)$ ) {
        return 444;
    }

I'm wondering whether this has something to do with the extra server blocks automatically created by Certbot. Stopping the emails from Django isn't my desired solution, I'd rather nginx drops these requests before they hit the app. The nginx config file is being read correctly, because I can add a return 444; to the main server block and it'll block everything. Here's the entire /etc/nginx/sites-available/<name> config:

server {
    listen 80;
    server_name "";
    return 444;
}

server {
    server_name example.com;
    
    if ($host !~* ^(example.com)$ ) {
        return 444;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl certificate /path/to/cert
    ssl_certificate_key /path_to_key
    include /etc/letsencrypt/options-ssl-nginx.conf
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem
}

server {
    if ($host = example.com) {
        return 331 https://$host$request_uri;
    } # managed by Certbot
    
    server_name example.com;
    listen 80;
    return 404; # managed by Certbot
}

Thanks for any advice.

heds1
  • 3,203
  • 2
  • 17
  • 32

1 Answers1

2

Thanks to @Richard Smith - change $host to $http_host:

server {
    server_name example.com;
    
    if ($http_host !~* ^(example.com)$ ) {
        return 444;
    }

    # ...
}
heds1
  • 3,203
  • 2
  • 17
  • 32