All posts

Fix NotFoundError in Flask in Production

Resolve Flask 404 errors in production caused by URL rules, blueprint registration, and static file serving behind reverse proxies.

Flask 404 Errors in Production

Flask routes that work in development but return 404 in production often point to blueprint registration, URL prefix, or static file serving issues.

Blueprint Not Registered

# blueprints/api.py
from flask import Blueprint

api_bp = Blueprint('api', __name__, url_prefix='/api')

@api_bp.route('/users')
def get_users():
    return jsonify(users)

# app.py — MUST register the blueprint!
from blueprints.api import api_bp
app.register_blueprint(api_bp)

Trailing Slash Behavior

Flask has strict trailing slash handling:

# With trailing slash — redirects /about to /about/
@app.route('/about/')
def about():
    return 'About'

# Without trailing slash — /about/ returns 404
@app.route('/about')
def about():
    return 'About'

In production behind a proxy, the redirect might break. Be consistent:

app.url_map.strict_slashes = False

APPLICATION_ROOT

If Flask runs under a subpath:

app.config['APPLICATION_ROOT'] = '/myapp'

# Or use ProxyFix
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_prefix=1)

Static Files in Production

Don't serve static files through Flask in production:

# Let Nginx handle static files
location /static {
    alias /var/www/myapp/static;
}

location / {
    proxy_pass http://127.0.0.1:8000;
}

Bugsly tracks 404 rates and captures the full URL, making it easy to spot misconfigured routes or broken links after deployment.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free