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

问题描述

我做了很多研究,并更改了代码以尝试解决此问题,但是没有任何效果。 Flask路由重定向现在可以与Nginx和Certbot一起正常使用。进入网站可以正常工作,单击导航中的链接也可以正常工作,但是当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','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;
    }