在后台使用Django和Gunicorn,每次我提交一个表单,应该被发送到example.com/pagetwo,我被发送到localhost/pagetwo。
我是Nginx的新手,所以如果有人能指出问题所在,我将非常感谢:)
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;
}
}下面是索引页面中的一个表单:
<form id='formone' method='POST' action=''> {% csrf_token %}
{{ form.as_p }}
<br />
<button type="submit" class="btn btn-success btn-sm">Submit</button>
</form>发布于 2015-09-22 17:04:47
在这种情况下,django正在监听某个unix套接字,并且nginx发送到django的所有请求都是本地的,所以django看到的主机是'localhost‘。
当你提交表单时,Django必须为任何重定向建立完整的URL。因为只有django知道的域是'localhost',所以django将使用该主机构建URL。
Nginx是django和客户端之间的网关,所以它负责修改django发送的所有重定向urls,以匹配nginx服务站点的域名。但是下面这行:
proxy_redirect off;告诉nginx“不要这么做,不要重写重定向的URL”。这导致了重定向问题。
您可以做的是:删除该行或更改nginx配置,使其正确地通知django有关域名的信息。为此,您应该添加以下代码行:
proxy_set_header Host $http_host;在config中使用这一行,nginx将把真实的域名传递给django,而不是传递localhost。这是推荐的方式,因为有了这一行,nginx对django会更透明。您还应该在此处添加其他标头配置行,以便django中的其他内容可以正常工作。有关所有配置的列表,请参阅您正在使用的wsgi服务器的文档,如果是gunicorn,它将是here。
发布于 2021-10-27 13:30:26
我使用了这个组合,为我解决了这个问题
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.
}https://stackoverflow.com/questions/32712443
复制相似问题