Python Flask url_for 生成 http URL 而不是 https
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14810795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask url_for generating http URL instead of https
提问by Blaise
I am using url_forto generate a redirect URL when a user has logged out:
我url_for用来在用户注销时生成重定向 URL:
return redirect(url_for('.index', _external=True))
However, when I changed the page to a httpsconnection, the url_forstill gives me http.
但是,当我将页面更改为https连接时,url_for仍然给我http。
I would like to explicitly ask url_forto add httpsat the beginning of a URL.
我想明确要求在 URL 的开头url_for添加https。
Can you point me how to change it? I looked at Flask docs, without luck.
你能指点我怎么改吗?我查看了 Flask 文档,但运气不佳。
采纳答案by Markus Unterwaditzer
With Flask 0.10, there will be a much better solution available than wrapping url_for. If you look at https://github.com/mitsuhiko/flask/commit/b5069d07a24a3c3a54fb056aa6f4076a0e7088c7, a _schemeparameter has been added. Which means you can do the following:
使用 Flask 0.10,将会有一个比 wrapping 更好的解决方案url_for。如果您查看https://github.com/mitsuhiko/flask/commit/b5069d07a24a3c3a54fb056aa6f4076a0e7088c7,_scheme则添加了一个参数。这意味着您可以执行以下操作:
url_for('secure_thingy',
_external=True,
_scheme='https',
viewarg1=1, ...)
_schemesets the URL scheme, generating a URL like https://..instead of http://. However, by default Flask only generates paths (without host or scheme), so you will need to include the _external=Trueto go from /secure_thingyto https://example.com/secure_thingy.
_scheme设置 URL 方案,生成一个 URL,https://..而不是http://. 但是,默认情况下 Flask 只生成路径(没有主机或方案),因此您需要包含_external=Trueto go from /secure_thingyto https://example.com/secure_thingy。
However, consider making your website HTTPS-only instead.It seems that you're trying to partially enforce HTTPS for only a few "secure" routes, but you can't ensure that your https-URL is not changed if the page linking to the secure page is not encrypted. This is similar to mixed content.
但是,请考虑让您的网站仅使用 HTTPS。似乎您试图仅对少数“安全”路由部分强制执行 HTTPS,但如果链接到安全页面的页面未加密,则无法确保您的 https-URL 不会更改。这类似于混合内容。
回答by dajobe
I tried the accepted answer with an url_forarg but I found it easier to use the PREFERRED_URL_SCHEMEconfig variable and set it to https with:
我用url_forarg尝试了接受的答案,但我发现使用PREFERRED_URL_SCHEMEconfig 变量并将其设置为 https更容易:
app.config.update(dict(
PREFERRED_URL_SCHEME = 'https'
))
since you don't have to add it to every url_forcall.
因为您不必将其添加到每个url_for电话中。
回答by cvrebert
Setting _schemeon every url_for()call is extremely tedious, and PREFERRED_URL_SCHEMEdoesn't seem to work. However, mucking with what the request's supposed scheme is at the WSGI level seems to successfully convince Flask to always construct HTTPS URLs:
_scheme每次url_for()通话都设置非常乏味,而且PREFERRED_URL_SCHEME似乎不起作用。然而,在 WSGI 级别处理请求的假设方案似乎成功说服 Flask 始终构建 HTTPS URL:
def _force_https(app):
def wrapper(environ, start_response):
environ['wsgi.url_scheme'] = 'https'
return app(environ, start_response)
return wrapper
app = Flask(...)
app = _force_https(app)
回答by aldel
If you want to affect the URL scheme for all server-generated URLs (url_forand redirect), rather than having to set _schemeon every call, it seems that the "correct" answer is to use WSGI middleware, as in this snippet: http://flask.pocoo.org/snippets/35/
如果您想影响所有服务器生成的 URL(url_for和redirect)的 URL 方案,而不是_scheme在每次调用时都设置,似乎“正确”的答案是使用 WSGI 中间件,如以下代码段所示:http:// flask.pocoo.org/snippets/35/
(This Flask bugseems to confirm that that is the preferred way.)
(这个 Flask 错误似乎证实这是首选方式。)
Basically, if your WSGI environment has environ['wsgi.url_scheme'] = 'https', then url_forwill generate https:URLs.
基本上,如果您的 WSGI 环境有environ['wsgi.url_scheme'] = 'https',那么url_for将生成https:URL。
I was getting http://URLs from url_forbecause my server was deployed behind an Elastic Beanstalk load balancer, which communicates with the server in regular HTTP. My solution (specific to Elastic Beanstalk) was like this (simplified from the snippet linked above):
我正在http://从中获取URL,url_for因为我的服务器部署在 Elastic Beanstalk 负载均衡器后面,该负载均衡器通过常规 HTTP 与服务器通信。我的解决方案(特定于 Elastic Beanstalk)是这样的(从上面链接的片段中简化):
class ReverseProxied(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
scheme = environ.get('HTTP_X_FORWARDED_PROTO')
if scheme:
environ['wsgi.url_scheme'] = scheme
return self.app(environ, start_response)
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
The Elastic Beanstalk-specific part of that is HTTP_X_FORWARDED_PROTO. Other environments would have other ways of determining whether the external URL included https. If you just want to always use HTTPS, you could unconditionally set environ['wsgi.url_scheme'] = 'https'.
其中 Elastic Beanstalk 特定的部分是HTTP_X_FORWARDED_PROTO. 其他环境有其他方法来确定外部 URL 是否包含 https。如果您只想始终使用 HTTPS,则可以无条件地设置environ['wsgi.url_scheme'] = 'https'.
PREFERRED_URL_SCHEMEis not the way to do this. It's ignored whenever a request is in progress.
PREFERRED_URL_SCHEME不是这样做的方法。每当请求正在进行时,它就会被忽略。
回答by Timothée Jeannin
If your are accessing your website through a reverse proxy like Nginx, then Flask correctly dectects the scheme being HTTP.
如果您通过像 Nginx 这样的反向代理访问您的网站,那么 Flask 会正确检测到该方案为HTTP.
Browser -----HTTPS----> Reverse proxy -----HTTP----> Flask
The easiest solution is to configure your reverse proxy to set the X-Forwarded-Protoheader. Flask will automatically detect this header and manage scheme accordingly. There is a more detailed explanation in the Flask documentation under the Proxy Setups section. For example, if you use Nginx, you will have to add the following line in your locationblock.
最简单的解决方案是配置反向代理以设置X-Forwarded-Proto标头。Flask 将自动检测此标头并相应地管理方案。Flask 文档中的 Proxy Setups 部分有更详细的解释。例如,如果您使用 Nginx,则必须在location块中添加以下行。
proxy_set_header X-Forwarded-Proto $scheme;
As other mentionned, if you can't change the configuration of your proxy, you can either use the werkzeug ProxyFix or build your own fix as described in the documentation: http://flask.pocoo.org/docs/0.12/deploying/wsgi-standalone/#proxy-setups
正如其他人提到的,如果您无法更改代理的配置,您可以使用 werkzeug ProxyFix 或按照文档中的说明构建您自己的修复程序:http://flask.pocoo.org/docs/0.12/deploying/ wsgi-standalone/#proxy-setups

