Nginx – How to Block Requests with Wrong Host Header

nginx

I use nginx to serve my website. I’d like to block all requests that come in with an HTTP “Host” header that doesn’t match my site’s domain.

To be more concrete, my nginx.conf contains these two server blocks:

server {
    # Redirect from the old domain to the new domain; also redirect
    # from www.newdomain.com to newdomain.com without the "www"
    server_name www.olddomain.com olddomain.com www.newdomain.com;
    listen 80;
    return 301 $scheme://newdomain.com$request_uri;
}

server {
    server_name newdomain.com localhost;
    listen 80;

    # Actual configuration goes here...
}

I’d like to block (i.e. “return” a 444 status code) any traffic whose Host isn’t www.olddomain.com, olddomain.com, www.newdomain.com, or newdomain.com. How can I do this?

Best Answer

Define a default server

if you don't explicitly define a default server, nginx will implicitly use the first-found server. so, just create a server block to block unknown hosts:

server {
  listen 80 default_server;
  return 444;
}

(no it's not necessary to add a server_name - since it will never be a match).