4

I'm using Django 1.5.1 in a production website but I'm having a huge number of 500's reports because of not allowed hosts requests. My website's Nginx vhost is configured as follows:

server {
    listen 80;
    server_name mywebsite.com.br;

    location / {
        uwsgi_pass unix:/opt/project/run/brmed_web.sock;
        include uwsgi_params;
    }
}

And I've set my allowed host settings on settings.py as:

ALLOWED_HOSTS = ['mywebsite.com.br']

Even though it works perfectly using my allowed host, I keep receiving erros as the following for stranges hosts:

Traceback (most recent call last):

  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 92, in get_response
    response = middleware_method(request)

  File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py", line 57, in process_request
    host = request.get_host()

  File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 72, in get_host
    "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host)

SuspiciousOperation: Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): 108.166.113.25

Some of the hosts, if not all ot them, are clearly malicious since their requests are trying to trick with some PHP stuff. More detail about one of the hosts can be found in this link.

My question is, what am I missing on Nginx configuration that is allowing these requests with these strange hosts to pass? FYI my Nginx just has this config file and its default config file.

bernardofontes
  • 327
  • 4
  • 10

1 Answers1

17

It depends on your default configuration, but from this answer on ServerFault you must define a default vhost in Nginx, otherwise it will use the first one as a default.

Basically, your configuration should look like this in order to allow only requests to "mywebsite.com.br" to pass:

server {
    listen 80 default_server;
    location / {
        # or show another site
        return 403 "Forbidden";
    }
}

server {
    listen 80;
    server_name mywebsite.com.br;
    location / {
        uwsgi_pass unix:/opt/project/run/brmed_web.sock;
        include uwsgi_params;
    }
}

If you need to also serve up other subdomains (www.mywebsite.com.br, etc.) you can set the server_name to ".mywebsite.com.br".

Community
  • 1
  • 1
Nicolas Cortot
  • 6,591
  • 34
  • 44
  • Hi! It worked perfectly! I didn't know that Nginx does this procedure when it does not match the correct server name. – bernardofontes Jun 18 '13 at 14:52
  • I had to add a ; after "Forbidden". Also if you need to also serve up other subdomains (www.mywebsite.com.br, etc.) you can set the server_name to ".mywebsite.com.br" – perrygeo Dec 16 '13 at 16:34
  • Just FYI - since 0.8.21 version nginx has changed the param name from "default" to "default_server". – aabele Jul 22 '15 at 12:08