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 :)
default.conf:
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>
</form>
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.
I used the combination of this which fixed the issue for me
location / {
proxy_set_header Host $http_host;
server_name_in_redirect off;
proxy_redirect off;
rewrite ^([^.]*[^/])$ https://my-website-url$1/ permanent; #This will add trailing / to the url which will solve the issue.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With