为什么 Nginx 一直将我重定向到本地主机?

Why does Nginx keep redirecting me to localhost?

在后端使用 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>

在这种情况下,django 正在监听一些 unix 套接字,并且 nginx 发送到 django 的所有请求都是本地的,所以 django 看到的主机是 'localhost'。

当您提交表单时,Django 必须为任何重定向构建完整的 URL。因为只有域 django 知道 'localhost',django 将使用该主机构建 URL。

Nginx 用作 django 和客户端之间的网关,因此它负责更改 django 发送的所有重定向 url 以匹配 nginx 正在服务的站点的域名。但是行:

        proxy_redirect off;

告诉 nginx "don't do that, don't rewrite that redirect URLs"。这导致了重定向问题。

您可以做的是:删除该行或更改 nginx 配置,以便正确通知 django 关于域名的信息。为此,您应该添加行:

        proxy_set_header Host $http_host;

通过配置中的那一行,nginx 会将真实域名传递给 django 而不是传递 localhost。这是推荐的方式,因为使用该行 nginx 对 django 将更加透明。您还应该在此处添加其他 header 配置行,以便 django 中的其他内容可以正常工作。有关所有配置的列表,请参阅您正在使用的 wsgi 服务器的文档,对于 gunicorn,它将是 here.

我结合使用了这个解决了我的问题

location / {
   proxy_set_header Host $http_host;
   server_name_in_redirect off;
   proxy_redirect off;
   rewrite ^([^.]*[^/])$ https://my-website-url/ permanent;   #This will add trailing / to the url which will solve the issue.
}