[英]How do I get the proxy scheme inside a Flask app?
我有一個 Flask 應用程序在 NGINX 反向代理后面運行。 在我的一個功能中,我需要將 URL 構建到不同的服務,並且我希望將 HTTP 方案與 NGINX 條目方案相匹配。 So if NGINX is reverse proxying an https request, I'd like to generate a url like https://my_other_service
. 但是,如果 NGINX 反向代理http
我希望它是http://my_other_service
。
The flask.url_for
function is able to automatically determine the proxy scheme when I use it for endpoints in the same app so I figure this must be possible, but in my case the url I'm generating is not an endpoint in the current Flask app .
如何確定 flask 應用程序中的代理方案?
如本問題所述,您可以在生成 URL 時直接告訴url_for
使用特定方案:
url_for('secure_thingy',
_external=True,
_scheme='https',
viewarg1=1, ...)
當然,問題在於您不一定知道 URL 是否應該是 https。 如果它在生產中運行在 Nginx 后面,它必須是 https。 如果它在 localhost 上運行以進行本地開發,則 https 可能不起作用。
一種解決方案是只為您的應用程序設置一個關於使用什么方案的配置設置。 在您的開發環境中,它將設置為 http。 在您的生產環境中,您將使用 https。 這就是我會做的。
另一種方法是告訴 Nginx 傳遞一個特殊的 header 然后您可以使用它來更改方案。
Nginx 網站上有關於添加標題的說明,所以這里有一個例子:
location /some/path/ {
proxy_set_header X-Force-Https "yes";
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://localhost:8000;
}
然后在您的 Flask 代碼中,僅將_scheme='https'
傳遞給url_for
if request.headers.get('X-Force-Https', None) == 'yes'
。
這是一個更加自動化的解決方案,但需要您修改生產 web 服務器環境。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.