Quantcast
Channel: 软件应用 –笑遍世界
Viewing all articles
Browse latest Browse all 51

Nginx+Gunicorn+Django出现“Bad Request (400)”

$
0
0

配置Nginx+Gunicorn+Django时,发现所有请求都是返回“Bad Request (400)”。

最开始,很直观地想到是Django的settings.py中配置的ALLOWED_HOSTS,检查了一下我的配置已经为:ALLOWED_HOSTS = [‘*’]表示允许所有的host。注:如果DEBUG=True,则不检查request header中的HTTP_HOST;只有关闭DEBUG模式才有这个检查。 这样的情况下,我就很奇怪了~~

后来找了好一阵子才忽然发现,我用Nginx作了反向代理,但是没有设置转发后request的host,所以关键要要加上“proxy_set_header Host $host;”的设置;后来,我是将proxy相关的信息放到proxy.conf文件中,然后在nginx.conf中“include proxy.conf”来引用。proxy.conf示例:https://github.com/smilejay/other-code/blob/master/config/nginx-proxy.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
client_max_body_size 20m;
client_body_buffer_size 256k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 128k;
proxy_buffers 4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;

这样配置了“proxy_set_header Host $host;”后,问题就解决了。
但是,还有一点儿没想得太明白,为啥 ALLOWED_HOSTS = [‘*’] 这个设置没有匹配上通过代理过来的请求;看文档是说通过 HttpRequest.get_host() 获得host,我打开DEBUG,不加”proxy_set_header Host $host;”,获得到了 request.get_host() 是我在nginx中通配置的”music_server”(因为配置为:proxy_pass http://music_server;)。其实仍不完全明白,暂且放一下吧。

参考文档:

https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts

https://www.digitalocean.com/community/questions/bad-request-400-django-nginx-gunicorn-on-debian-7

https://www.packtpub.com/books/content/using-nginx-reverse-proxy

http://nginx.com/resources/admin-guide/reverse-proxy/

Original article: Nginx+Gunicorn+Django出现“Bad Request (400)”

©2015 笑遍世界. All Rights Reserved.


Viewing all articles
Browse latest Browse all 51

Trending Articles