'Flask app routing not working with Nginx and uwsgi

I have a simple Flask application setup based on this tutorial. Everything works except when I add another route to the application file.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"

@app.route("/user")
def user():
    return "<h1>Hello user</h1>"

if __name__ == "__main__":
    app.run(host='0.0.0.0')

If I go to my IP address I can see "Hello There!"

However, IP/user gives me a 404 response

I have been browsing other similar kinds of questions but couldn't find how to get it to work.

What am I missing?

The Nginx file:

server {
    listen 80;
    server_name IP_address;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/username/project/project.sock;
    }
}


Solution 1:[1]

What is going on is that Nginx treats the location / as a request to only serve the IP_address URI and treat anything that looks like IP_address/some/other URI as something that you do not wish to server to the internet.

The flask stuff is OK but Nginx has to pass the requests to flask. You could simply change the config file to look like:

server {
    listen 80;
    server_name IP_address;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/username/project/project.sock;
    }

    location /user {
        include uwsgi_params;
        uwsgi_pass unix:/home/username/project/project.sock;
    }
}

Alternatively you can search in the Nginx documentation how to proxy all subpaths of / to uwsgi in a singlelocation configuration file directive instead of adding location by location all routes you wish to add to the flask application. There should a way to do that with a regular expression in the location directive.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 branco