不允许使用Nginx的主机避免Django的500错误

ber*_*tes 4 django nginx

我在生产网站上使用Django 1.5.1,但由于不允许主机请求,我有大量500的报告.我的网站的Nginx vhost配置如下:

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

    location / {
        uwsgi_pass unix:/opt/project/run/brmed_web.sock;
        include uwsgi_params;
    }
}
Run Code Online (Sandbox Code Playgroud)

我将允许的主机设置设置settings.py为:

ALLOWED_HOSTS = ['mywebsite.com.br']
Run Code Online (Sandbox Code Playgroud)

即使它使用我允许的主机完美地工作,我仍然收到以下奇怪主机的错误:

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
Run Code Online (Sandbox Code Playgroud)

一些主机,如果不是全部主机,显然是恶意的,因为他们的请求试图欺骗一些PHP的东西.有关其中一个主机的更多详细信息,请参见此链接.

我的问题是,我在Nginx配置上缺少什么,允许这些奇怪主机的这些请求通过?仅供参考我的Nginx只有这个配置文件及其默认配置文件.

Nic*_*tot 14

这取决于您的默认配置,但是在ServerFault上的这个答案中,您必须在Nginx中定义默认vhost,否则它将使用第一个作为默认值.

基本上,您的配置应该如下所示,以便只允许"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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您还需要提供其他子域(www.mywebsite.com.br等),则可以将server_name设置为".mywebsite.com.br".