Flask Redirect 使用 Nginx 和 Certbot 创建无效 URL

Flask Redirect Creates Invalid URL with Nginx and Certbot

我进行了大量研究并修改了代码以尝试解决此问题,但没有任何效果。 Flask 路由重定向现在可以与 Nginx 和 Certbot 一起正常工作。访问该网站工作正常,在导航中单击 link 工作正常,但是当 Flask 尝试重定向到另一个 URL (Flask 路由)时,它会创建一个无效的 URL,看起来像这样:

https://example.com/signup

提交表单 (POST) 请求后,这是我看到的 URL。


https://example.com,example.com/login

这是 Flask Python 代码:

@main.route('/signup', methods=['GET', 'POST'])
def sign_up():
    '''sign up user'''
    
    form = SignupForm()
    if form.validate_on_submit():
        return redirect(url_for('main.login'))
    return render_template('main/signup.html', form=form)

@main.route('/login', methods=['GET', 'POST'])
def login():
    '''login user'''

    form = LoginForm()
    if form.validate_on_submit():
        pass
    return render_template('main/login.html', form=form)

Nginx网站配置:

server {

    server_name example.com www.example.com;
    
    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/example/example.sock;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP     $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {

    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    server_name example.com www.example.com;
    return 404; # managed by Certbot

}

如果我手动输入它,它就可以工作,这意味着 Python/Flask 代码没问题。

https://example.com/login

解决方案在 Nginx 位置块中。请注意行 include proxy_params;。它最终包含了两次相同的信息。

location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/example/example.sock;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP     $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
    }

由于文件 /etc/nginx/proxy_params 包含 proxy_set_header 信息,因此我不必再次添加它。位置块现在看起来像这样。

location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/example/example.sock;
    }