Nginx configuration for static sites in root directory, Flask apps in subdirectories


I'd like to have a static site in my root public_html directory, then Flask apps in their own subdirectories (e.g. public_html/foo). The static root directory functions as expected.

I have spent hours editing the nginx configuration to get the Flask apps working, but always end up back in the same place, namely that the following code always returns 'Bad Config' when I migrate to mysite/foo. I want it to return 'Hello World!'

If I alter the nginx configuration so that the server root is in public_html/foo, the Flask applications work as expected (i.e. returns 'Hello World!'). In the following configuration, the Flask index still points to when I believe it should point to


upstream frontends {
# gunicorn

server {
listen 80;
rewrite ^/(.*)$1 permanent;

server {
listen 80;
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;


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

def index():
    return 'Hello World!'

def test():
    return 'Bad config'

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

if __name__ == '__main__':


workers = 2
bind = ''
proc_name = 'foo_gunicorn'
pidfile = ''

Flask is launched with gunicorn -c foo:app


Adding rewrite /foo/(.*) /$1 break; to the nginx location /foo block makes mysite/foo return 'Hello World', however all its links (such as those to the stylesheet from a template) still point to the site root (e.g. mysite/static/style.css instead of mysite/foo/static/style.css)

9/4/2013 5:16:52 PM

Accepted Answer

Got an answer from mitsuhiko (Flask lead dev):

You need to define a ReverseProxied class in your Flask app and add several proxy-set-header lines to the location /foo block in the nginx config.

9/27/2011 4:55:40 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow