Reputation: 783
I am trying to use flask + gunicorn + nginx to set up a web app. It's ok by running the script, but it has some little problem in nginx.
In the hello.py
, it should redirect to index after submit a form. In my local test, the index address is http://127.0.0.1:8080 and everything goes well.
With the server of nginx and gunicorn, when a submit the form, it will redirect to http://192.168.1.108/ instead of http://192.168.1.108:1025/. 192.168.1.108 here is my local ip.
code redirect to index.html in hello.py
, the cody is clone from 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()
setting in the 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;
}
}
}
Running gunicorn bygunicorn -w 2 -b 127.0.0.1:8080 manage:app
.
I think there is something wrong in the nginx configue.
Upvotes: 2
Views: 2393
Reputation: 5744
I suspect that your issue is that nginx is not passing the port along with the Host header to gunicorn, so that your app thinks it's running on the default port instead of 8080. Try chaning your first proxy_set_header in nginx to this:
proxy_set_header Host $host:$server_port;
Upvotes: 2