【问题标题】:Nginx configuration for static sites in root directory, Flask apps in subdirectories根目录中静态站点的 Nginx 配置,子目录中的 Flask 应用程序
【发布时间】:2013-09-05 01:16:52
【问题描述】:

我想在我的 public_html 根目录中创建一个静态站点,然后在它们自己的子目录中创建 Flask 应用程序(例如 public_html/foo)。静态根目录按预期运行。

我花了几个小时编辑 nginx 配置以使 Flask 应用程序正常工作,但最终总是回到同一个地方,即当我迁移到 mysite/foo 时,以下代码总是返回“错误配置”。我希望它返回“Hello World!”

如果我更改 nginx 配置以使服务器根目录位于 public_html/foo 中,Flask 应用程序将按预期工作(即 mysite.com 返回“Hello World!”)。在以下配置中,当我认为 Flask 索引应该指向 mysite.com/foo 时,它仍然指向 mysite.com

/etc/nginx/sites-enabled/mysite

upstream frontends {
# gunicorn
server 127.0.0.1:18000;
}

server {
listen 80;
server_name www.mysite.com;
rewrite ^/(.*) http://mysite.com$1 permanent;
}

server {
listen 80;
server_name mysite.com;
server_name_in_redirect off;
root /home/ubuntu/public_html/mysite;

access_log /home/ubuntu/logs/mysite/access.log;
error_log /home/ubuntu/logs/mysite/error.log;

location / {
    index index.html;
    }
location /foo {
    try_files $uri @foo;
    }
location @foo {
        proxy_pass http://frontends;
        break;
    }
}

/home/ubuntu/public_html/mysite/foo/foo.py

from flask import Flask
from flask import render_template
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World!'

@app.route('/foo')
def test():
    return 'Bad config'

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

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

/home/ubuntu/public_html/mysite/foo/deploy.py

workers = 2
bind = '127.0.0.1:18000'
proc_name = 'foo_gunicorn'
pidfile = 'foo.pid'

Flask 使用 gunicorn -c deploy.py foo:app 启动

更新

rewrite /foo/(.*) /$1 break; 添加到 nginx location /foo 块使 mysite/foo 返回“Hello World”,但是它的所有链接(例如从模板到样式表的链接)仍然指向站点根目录(例如 mysite/static /style.css 而不是 mysite/foo/static/style.css)

【问题讨论】:

    标签: python nginx flask gunicorn


    【解决方案1】:

    得到了 mitsuhiko(Flask 首席开发人员)的回答: http://flask.pocoo.org/snippets/35/

    您需要在 Flask 应用程序中定义一个 ReverseProxied 类,并在 nginx 配置中的 location /foo 块中添加几行 proxy-set-header 行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多