Nginx as a reverse proxy helps your Flask app handle many users smoothly. It acts like a friendly gatekeeper that forwards requests to your app and sends back responses.
0
0
Nginx as reverse proxy in Flask
Introduction
You want to serve your Flask app to many users without slowing down.
You want to hide your Flask app server details from the internet.
You want to add security features like HTTPS easily.
You want to balance traffic between multiple Flask app instances.
You want to serve static files quickly alongside your Flask app.
Syntax
Flask
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1:5000;
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;
}
}proxy_pass tells Nginx where your Flask app is running (usually localhost with port 5000).
Headers like X-Real-IP help your Flask app know the real visitor's IP address.
Examples
Forward only requests starting with /api/ to the Flask app's /api/ path.
Flask
location /api/ {
proxy_pass http://127.0.0.1:5000/api/;
}Serve static files directly from Nginx without passing to Flask.
Flask
location /static/ {
alias /var/www/static/;
}Use Nginx to handle HTTPS and forward requests to Flask.
Flask
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://127.0.0.1:5000;
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;
}
}Sample Program
This simple Flask app runs on localhost port 5000. Nginx will forward web requests to it.
Flask
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello from Flask behind Nginx!' if __name__ == '__main__': app.run(host='127.0.0.1', port=5000)
OutputSuccess
Important Notes
Make sure Nginx and Flask are running on the same machine or network.
Restart Nginx after changing its config with sudo systemctl restart nginx.
Check Nginx error logs if things don't work: usually at /var/log/nginx/error.log.
Summary
Nginx as a reverse proxy forwards web requests to your Flask app.
This setup improves performance, security, and scalability.
You configure Nginx with proxy_pass to point to your Flask app.