Nginx – serve only with backend or 404, no static files in root

configurationflasknginxuwsgi

I am trying to serve all requests with the backend (uwsgi for flask in this case) and if the backend has no such path, nginx should return 404.

Somehow I only can get the backend to take over when I use

try_files $uri @uwsgi;

But that way, you can access all files in the root directory. I don't want to serve all files in the root directory.

I also tried this:

try_files @uwsgi =404;

But then I get an 404 even if the path is defined in my flask app.

More context:
Ubuntu 14.04, nginx 1.4.6

    location @uwsgi {
            include uwsgi_params;
            uwsgi_pass unix:$document_root/myapp.sock;
    }

    location / {
            try_files $uri @uwsgi;
    }

    location /static/ {
            try_files $uri =404;
    }

The flask app is like this:

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

So when I visit example.com/test I want to have the flask backend handle this. But I don't want nginx to serve all files in the root directory.

Best Answer

Why use try_files if you never have any files you want to try and you always want to pass to your WSGI handler? Did you try simply making uwsgi_pass the root location?

location / {
    include uwsgi_params;
    uwsgi_pass unix:$document_root/myapp.sock;
}

You can combine it with a static location/static server name that serves files out of a regular folder but only for that static URL.