[英]Django + Gunicorn + Nginx: Bad Request (400) in Debug=True
I'm trying to run my server with Django, nginx and gunicorn. 我正在尝试使用Django,nginx和gunicorn运行我的服务器。 On the development Server, everything went fine. 在开发服务器上,一切都很顺利。 But on the production server, gunicorn always returns a Bad Request (400). 但是在生产服务器上,gunicorn总是返回Bad Request(400)。
I'm aware that I need to set my ALLOWED_HOSTS
variable, and I did. 我知道我需要设置ALLOWED_HOSTS
变量,我做了。 I tried the correct domain, an asterisk, or even setting DEBUG to True. 我尝试了正确的域名,星号,甚至将DEBUG设置为True。 But still, it's always Bad Request (400). 但是,它仍然是Bad Request(400)。
Here is my nginx-config: 这是我的nginx-config:
server {
listen 80;
location /static {
alias /home/username/sites/sub.domain.example.com/static;
}
location / {
proxy_set_header Host $http_host;
proxy_pass http://localhost:8000;
}
}
My wsgi-prod.py
file: 我的wsgi-prod.py
文件:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings_prod")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
The settings_prod.py
file (shortened): settings_prod.py
文件(缩写):
DEBUG = False
ALLOWED_HOSTS=["*"]
I start gunicorn the following way (with virtualenv): 我用以下方式开始使用gunicorn(使用virtualenv):
gunicorn --bind 127.0.0.1:8000 app.wsgi_prod:application
When I start the server with manage.py runserver --settings=app.settings_prod
, the site is accessible. 当我使用manage.py runserver --settings=app.settings_prod
启动服务器时,该站点是可访问的。 gunicorn's error log shows nothing, and the access log only shows the 400. The static content does work. gunicorn的错误日志显示什么,访问日志只显示400.静态内容确实有效。
You should tell Nginx to pass the host to Gunicorn like this: 您应该告诉Nginx将主机传递给Gunicorn,如下所示:
proxy_set_header Host $host;
Additionally I would pass these values (example) also so you have access to the IP of the request: 另外,我也会传递这些值(示例),以便您可以访问请求的IP:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
Please also check your Nginx Logs if you haven´t done so. 如果您还没有这样做,也请检查您的Nginx日志。 I hope this helps. 我希望这有帮助。
EDIT: Try also to set set server name like: 编辑:尝试也设置设置服务器名称,如:
server_name your_domain.com www.your_domain.com
Last but not least try to set your environment like this (solution in this case): 最后但并非最不重要的是尝试像这样设置您的环境(在这种情况下的解决方案):
os.environ['DJANGO_SETTINGS_MODULE'] = "app.settings_prod"
This fixed it for me: 这为我修好了:
location / {
proxy_pass http://127.0.0.1:8081;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.