ALLOWED_HOSTS Digital Ocean 上的 Django 应用程序出错。设置变量不能解决错误

ALLOWED_HOSTS error in Django app on Digital Ocean. Setting the variable does not resolve the error

我按照本指南在 DO 上设置了一个 Django 应用程序:

https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04

但是,我无法克服常见的 ALLOWED_HOSTS 错误,每个人通常都会忘记在列表中添加任何内容,这是一个简单的修复方法。即使输入了正确的值,或者使用了包罗万象的“*”,错误仍然存​​在。我以前从未遇到过这种情况,所以我会把我的配置文件放在这里,以便更多地关注它。关于可能导致此问题的原因有什么想法吗?

/etc/uwsgi/sites/myapp.ini 的内容:

[uwsgi]
project = myapp
uid = myuser
base = /home/%(uid)

chdir = %(base)/%(project)
home = %(base)/%(project)/venv
module = %(project).wsgi:application

master = true
processes = 5

socket = /run/uwsgi/%(project).sock
chown-socket = %(uid):www-data
chmod-socket = 660
vacuum = true

/etc/systemd/system/uwsgi.服务的内容:

[Unit]
Description=uWSGI Emperor service

[Service]
ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown myuser:www-data /run/uwsgi'
ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all

[Install]
WantedBy=multi-user.target

/etc/nginx/sites-available/myapp的内容:

server {
    listen 80;
    server_name mydomain.com www.mydomain.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/myuser/myapp_static;
    }

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/run/uwsgi/myapp.sock;
    }
}

更新

浏览器中显示的错误消息:

DisallowedHost at /
Invalid HTTP_HOST header: 'mydomain.com'. You may need to add 'mydomain.com' to ALLOWED_HOSTS.
Request Method: GET
Request URL:    mydomain.com
Django Version: 1.11
Exception Type: DisallowedHost
Exception Value:    
Invalid HTTP_HOST header: 'mydomain.com'. You may need to add 'mydomain.com' to ALLOWED_HOSTS.
Exception Location: /home/myuser/myapp/venv/lib/python3.5/site-packages/django/http/request.py in get_host, line 113
Python Executable:  /usr/local/bin/uwsgi
Python Version: 3.5.2
Python Path:    
['.',
 '',
 '/usr/lib/python35.zip',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-x86_64-linux-gnu',
 '/usr/lib/python3.5/lib-dynload',
 '/home/myuser/myapp/venv/lib/python3.5/site-packages']

哦,现在这很有趣。根据 django 错误页面,ALLOWED_HOSTS 的当前值是我服务器的 ip 地址(当然在列表中)。但它现在在 settings.py 文件中肯定设置为 ['*']。什么可能会覆盖该变量?

您应该在 Django settings.py 中适当地设置 ALLOWED_HOSTS。像这样。

ALLOWED_HOSTS = ['mydomain.com', 'www.mydomain.com']

Digital ocean那篇文章也是这么写的。好好再看看吧

哇,好的,我找到了。我很困惑,因为 ALLOWED_HOSTS 的值没有更新,我一直在重启 nginx。但这里的解决方案是使用以下方式重新启动 UWSGI:

sudo systemctl 重启 uwsgi

以前用其他 Django 技术栈不需要这样做,但现在我知道了。