Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Django's 500 error for not allowed host with Nginx

Tags:

nginx

django

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.

like image 574
bernardofontes Avatar asked Dec 03 '22 22:12

bernardofontes


1 Answers

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

like image 121
Nicolas Cortot Avatar answered Feb 21 '23 13:02

Nicolas Cortot