极客老张
8/27/2025
Hey Flask friends! 👋 I'm stuck on something weird with response headers and could really use your wisdom.
Here's the situation: I've got a Flask app running behind nginx with uWSGI, and I'm seeing some magic happening with the Location header that I can't explain. 🧙♂️
I tried debugging by adding this simple after_request hook:
```python
@app.after_request
def add_header(response):
print(response.headers) # Just wanna see what's going on!
return response
In my uWSGI logs, I see this clean output:
Content-Type: text/html; charset=utf-8
Content-Length: 208
Location: /
But when I check the actual packet capture between uWSGI and nginx... boom! The Location header suddenly grows a full URL:
Location: http://<some-full-url>/m/
What gives? 🤔 I've checked:
This is driving me nuts because I need to control the exact Location header for some API clients. Anyone run into this before? Is this some nginx magic I don't know about?
PS: Bonus points if you can explain why the logs show one thing but the packets show another - that's the real head-scratcher for me! 🤯
#flask #webdev #helpalldevout
架构师小王
8/27/2025
Hey there! 👋 Oh man, I feel your pain with this header mystery - I spent a whole afternoon debugging something similar last year! It's one of those "why is this happening?!" moments that makes you question reality. 😅
Here's the scoop: what you're seeing is actually nginx being "helpful" (read: overly opinionated) with your Location headers. By default, nginx will rewrite relative redirects to absolute URLs when it's acting as a reverse proxy.
You've got two good options:
location / { proxy_pass http://uwsgi_backend; proxy_redirect off; # This is the magic line! }
from flask import redirect, url_for @app.route('/redirect-me') def redirect_me(): # Use _external=True if you WANT absolute URLs # Or leave it out for relative paths return redirect(url_for('index', _external=False))
The logs vs. packets difference happens because:
Location: /
)curl -v
to see raw headersSERVER_NAME
in Flask config - it can trigger this too!app.config['PREFERRED_URL_SCHEME'] = 'http' # or https
This one got me good last time - nginx will also add ports if you're not careful with proxy_set_header Host $host;
!
Hang in there! Header wrangling can be tricky, but once you understand the proxy layers, it gets much easier. Let me know if you need help tweaking the nginx config further - we'll get this sorted! 💪
#Flask #Nginx #WebDevTips #DebuggingWarStories