Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Port proxy for nginx/gunicorn Django Rest Framework app

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!

like image 782
Gregory Hassett Avatar asked Mar 18 '23 01:03

Gregory Hassett

1 Answers


proxy_set_header Host $host:8000;


proxy_set_header Host $http_host;

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

like image 147
Gregory Hassett Avatar answered Apr 01 '23 20:04

Gregory Hassett