问题描述
我正在使用gunicorn和nginx将传入的请求路由到我的Django Rest Framework API.
I am using gunicorn and nginx to route incoming requests to my Django Rest Framework API.
gunicorn在端口8001上运行,nginx在端口8000上运行.根据以下配置文件,nginx配置为将请求转发到gunicorn:
gunicorn is running on port 8001, nginx is running on port 8000. nginx is configured to forward requests to gunicorn, as per the following config file:
server {
listen 8000;
server_name ec2-ww.xx.yy.zz.compute-1.amazonaws.com; # public address of my server, redacted for stack overflow
access_log /vol/logs/ftv.access.log;
location ^~ /static/ {
alias /vol/server/ftv/static/;
autoindex on;
}
location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov) {
#access_log off;
expires 30d;
}
location / {
proxy_pass_header Server;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_set_header Host $host:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://ec2-ww.xx.yy.zz.compute-1.amazonaws.com:8001/;
}
}
我遇到的问题是DRF的HyperlinkedModelSerializer返回指向8001端口而不是8000端口的url. (我猜是因为)因为Django Rest Framework不了解gunicorn或nginx,只是看到请求从端口8001进入,因此它基于该端口形成了URL超链接.
The problem I'm having is that DRF's HyperlinkedModelSerializer returns url's that point to the 8001 port, instead of the 8000 port. This is (I guess) because Django Rest Framework, unaware of gunicorn or nginx, just sees the request coming in on port 8001, and so it forms its URL hyperlinks based upon that port.
我必须在我的Nginx conf文件或settings.py(或两者)中缺少某些配置选项,但是(对我而言)令人惊讶的是,以前没有问过/回答过这个问题-我一直在搜索. DRF或nginx专家的任何帮助将不胜感激!
I must be missing some configuration option in my nginx conf file, or in settings.py (or both) but, amazingly (to me), this question hasn't been asked/answered before -- I've been searching. Any help from DRF or nginx experts would be very much appreciated!
推荐答案
更改
proxy_set_header Host $host:8000;
到
proxy_set_header Host $http_host;
nginx配置文件中的
似乎已解决了该问题-
in the nginx configuration file seems to have fixed the issue --
这篇关于nginx/gunicorn Django Rest Framework应用程序的端口代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!