17

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?

2 Answers 2

22

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

0

Interestingly I had "-" as host header some times and this seems not to be caught by @AD7Six's answer (?). At least in my case it didn't work.

So I modified this referrer spam blog post entry a little bit and it works like a charm:

if ($http_host ^~ (myhostpattern.com) {
    return 405;
}

Don't know if this is the best solution but it keeps scraping robots away from my site.

You must log in to answer this question.

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