CodexBloom - Programming Q&A Platform

Flask app returning 404 for static files in a production environment using Nginx and Gunicorn

šŸ‘€ Views: 5821 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-08
flask nginx gunicorn static-files Python

I need help solving I keep running into I'm currently running a Flask application in a production environment using Nginx as the reverse proxy and Gunicorn as the WSGI server... While the application routes are working perfectly, I’m working with a frustrating scenario where requests for static files are returning a 404 behavior. The directory structure of my project looks like this: ``` /my_flask_app /static /css /js /templates app.py wsgi.py ``` In my Flask app, I have set the static folder like this: ```python from flask import Flask app = Flask(__name__, static_folder='static') @app.route('/') def home(): return render_template('index.html') ``` I configured Nginx to serve static files directly like so: ```nginx server { listen 80; server_name mydomain.com; location /static { alias /path/to/my_flask_app/static; } location / { proxy_pass http://127.0.0.1:8000; 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; } } ``` However, when I try to access a static file like `http://mydomain.com/static/css/style.css`, I get a 404 Not Found behavior. I've double-checked the file's existence in the `/static/css` directory, and it's definitely there. I also inspected the Nginx behavior log, which shows `open() "/path/to/my_flask_app/static/css/style.css" failed (No such file or directory)`, even though the path seems correct. I've tried reloading Nginx and checking the permissions of the static files as well, ensuring they are readable by Nginx. I'm using Nginx version 1.18 and Gunicorn version 20.1.0. Any advice on why the static files are not being served correctly? Am I missing something in the Nginx configuration or file paths? I'm on Windows 10 using the latest version of Python. What am I doing wrong? I'm coming from a different tech stack and learning Python.