4
votes

I am using gunicorn and nginx to route incoming requests to my Django Rest Framework API.

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/;
    }
}

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.

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!

3

3 Answers

7
votes

Changing

proxy_set_header Host $host:8000;

to

proxy_set_header Host $http_host;

in the nginx configuration file seems to have fixed the issue --

0
votes

Changing

proxy_set_header Host $host:8000;

to

proxy_set_header Host $http_host;

worked for me.

Also I had to add host name to ALLOWED_HOST field in settings.py file.

0
votes

I am using wsgi, nginx and Django. Actually i want to redirect the request on multiple port on same IP address. How to do this.

I have one url, for example "mysite.com". When its called i want server to process request on different port. Every thing will be same like only one instance, same url but server should redirect the request on different port. mysite.com:8080, mysite.com:8001, mysite.com:8002, etc for load balancing. How to do it in nginx.