Avoid Django 500 Errors for an Invalid Nginx Host

I use Django 1.5.1 on the website, but I have a huge number of 500 reports due to invalid hosts. My Nginx vhost site 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 set the valid host settings.py to settings.py as:

 ALLOWED_HOSTS = ['mywebsite.com.br'] 

Although it works fine with my resolved host, I keep getting erros like this 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 of them, are clearly harmful, as their requests try to trick some PHP stuff. More information about one of the hosts can be found in this link .

My question is: what am I missing in the Nginx configuration that allows these requests with these strange hosts to go through? FYI my Nginx has only this configuration file and its default configuration file.

+4
source share
1 answer

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

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

 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 also need to serve other subdomains (www.mywebsite.com.br, etc.), you can set the server_name to ".mywebsite.com.br".

+14
source

Source: https://habr.com/ru/post/1486634/


All Articles