To set up Nginx as a reverse proxy for a Flask application running in a subdirectory, you'll need to configure both your Flask application and the Nginx server block. Below are the steps you can follow to achieve this:
Step 1: Configure Flask Application
First, you need to make sure your Flask application is aware that it's being served from a subdirectory. You can use the APPLICATION_ROOT configuration to specify the path.
In your Flask application, set the APPLICATION_ROOT:
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/subdirectory'
Or, if you're using blueprints, you can specify the url_prefix:
from flask import Blueprint
bp = Blueprint('my_blueprint', __name__, url_prefix='/subdirectory')
Step 2: Set Up Nginx Reverse Proxy
Next, configure your Nginx server block to reverse proxy requests to the Flask application. Create or edit an existing configuration file in /etc/nginx/sites-available/ and create a symbolic link to it in /etc/nginx/sites-enabled/ if necessary.
Here's an example Nginx configuration that sets up a reverse proxy for a Flask application running on localhost:5000 and served under the /subdirectory path:
server {
listen 80;
server_name example.com;
location /subdirectory {
# Correct the $uri to avoid double '/subdirectory' prefix
rewrite ^/subdirectory(.*)$ $1 break;
# Proxy pass to the Flask server
proxy_pass http://localhost:5000;
# Set headers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Handle WebSockets
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Correct the SCRIPT_NAME header that WSGI uses
proxy_set_header SCRIPT_NAME /subdirectory;
}
# Optionally, handle static files directly by Nginx
location /subdirectory/static {
alias /path/to/your/flask/static/folder;
}
}
Make sure to replace /subdirectory, example.com, http://localhost:5000, and /path/to/your/flask/static/folder with the actual subdirectory, domain name, Flask application's address, and path to your static folder, respectively.
Step 3: Restart Nginx
After making changes to the Nginx configuration, you'll need to restart the Nginx service for the changes to take effect:
sudo systemctl restart nginx
Step 4: Test the Configuration
Finally, test your setup by navigating to http://example.com/subdirectory in your web browser. If everything is correctly configured, you should see your Flask application's landing page.
Remember that serving a Flask application in production usually requires a WSGI server like Gunicorn or uWSGI, which sits between Nginx and Flask. The proxy_pass would then point to the WSGI server instead of Flask's development server.