【问题标题】:flask+nginx+gunicorn redirect error烧瓶+nginx+gunicorn重定向错误
【发布时间】:2017-05-11 22:47:29
【问题描述】:

我正在尝试使用flask + gunicorn + nginx 来设置一个网络应用程序。运行脚本就可以了,但是在nginx里面有点小问题。

hello.py 中,它应该在提交表单后重定向到索引。在我本地测试中,索引地址为http://127.0.0.1:8080,一切顺利。
使用 nginx 和 gunicorn 的服务器,当提交表单时,它将重定向到 http://192.168.1.108/ 而不是 http://192.168.1.108:1025/。 192.168.1.108 这里是我的本地ip。

代码重定向到hello.py中的index.html,代码是从flasky克隆的。

from flask import Flask, render_template, session, redirect, url_for, flash
from flask_script import Manager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from werkzeug.contrib.fixers import ProxyFix


app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.config['SECRET_KEY'] = 'hard to guess string'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)


class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')


@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))


if __name__ == '__main__':
    manager.run()

在nginx中设置:

worker_processes  2;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    server {
        listen       1025;
        server_name  127.0.0.1:8080;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://127.0.0.1:8080;   # gunicorn host address
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

gunicorn -w 2 -b 127.0.0.1:8080 manage:app 运行 gunicorn。 我认为 nginx 配置有问题。

【问题讨论】:

    标签: python nginx flask


    【解决方案1】:

    我怀疑您的问题是 nginx 没有将端口与 Host 标头一起传递给 gunicorn,因此您的应用程序认为它在默认端口而不是 8080 上运行。尝试将 nginx 中的第一个 proxy_set_header 更改为:

    proxy_set_header Host $host:$server_port;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2017-11-12
      • 2014-11-13
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多