Why does Nginx keep redirecting me to localhost?


Using Django on the backend with Gunicorn, each time I submit a form and am supposed to be sent to example.com/pagetwo I am sent to localhost/pagetwo instead.

I’m new to Nginx so if someone could point out what the problem is I’d be most greatful 🙂


server {
    listen       80;
    server_name  example.com;

    location /static/ {
        root /srv;

    location / {
        proxy_redirect off;
        proxy_pass http://unix:/srv/sockets/website.sock;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;

Here is a form from the index page:

<form id='formone' method='POST' action=''> {% csrf_token %}
    {{ form.as_p }}
    <br />
    <button type="submit" class="btn btn-success btn-sm">Submit</button>


In this situation, django is listening on some unix socket and all requests sent to django by nginx are local, so host that django sees is ‘localhost’.

Django must build full URL for any redirection when you’re submitting form. Because only domain django knows about is ‘localhost’, django will build URL using that host.

Nginx is used as gateway between django and clients, so it is responsible for changing all redirect urls sent by django to match domain name that nginx is serving site on. But line:

        proxy_redirect off;

is telling nginx “don’t do that, don’t rewrite that redirect URLs”. That is causing redirection problem.

What you can do is: remove that line or change nginx configuration in way that it will properly inform django about domain name. To do that, you should add line:

        proxy_set_header Host $http_host;

With that line in config, nginx will pass real domain name to django instead of passing localhost. This is recommended way, because with that line nginx will be more transparent to django. There are also other header configuration lines that you should add here, so other things in django can work properly. For list of all configuration refer to documentation of wsgi server that you are using, for gunicorn it will be here.

Answered By – GwynBleidD

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published