在Django上永久将http重定向到Google App Engine Flexible上的https
我正在一个项目中使用Django在Python 3 Flexible Environment中使用Google Cloud Platform的App Engine,并且我试图将所有路径上所有通过http
的请求永久重定向到https
,但是到目前为止还没有成功.我可以通过https
来访问该站点,但前提是必须在地址栏中明确写出该消息.
I'm working on a project that uses Google Cloud Platform's App Engine in the Python 3 Flexible Environment using Django, and I'm trying to permanently redirect all requests over http
to https
for all routes, but so far have not been successful. I can access the site over https
, but only if explicitly written in the address bar.
我看了这篇文章:如何永久将"http://"和"www." URL重定向到"https://"?,但没有找到答案.
I've looked at this post: How to permanently redirect `http://` and `www.` URLs to `https://`? but did not find the answer useful.
除了重定向外,该应用在各种意义上均正常运行.这是我的app.yaml
文件:
The app works properly in every sense except for the redirecting. Here is my app.yaml
file:
# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT myproject.wsgi
runtime_config:
python_version: 3
# [END runtime]
在myproject/settings.py
中,我定义了以下变量:
In myproject/settings.py
I have these variables defined:
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP-X-FORWARDED-PROTO', 'https')
在我的本地计算机上,当我将SECURE_SSL_REDIRECT
设置为True
时,即使本地主机不支持SSL,我也被正确地重定向到了https
.在生产中,我仍然可以仅使用http
来访问该站点.
On my local machine, when I set SECURE_SSL_REDIRECT
to True
, I was redirected to https
properly, even though SSL is not supported on localhost. In production, I am still able to access the site using just http
.
是否缺少某些内容或做错了什么导致重定向不发生?
Is there something I'm missing or doing wrong to cause the redirect not to happen?
在app.yaml中设置secure
仅适用于GAE Standard,而不适用于Flexible. 针对Flexible的app.yaml文档未提及此内容根本不重要.
Setting secure
in app.yaml only works for GAE Standard but not in Flexible. The app.yaml docs for Flexible do not mention this key at all.
您可能必须在应用程序级别通过检查X-Forwarded-Proto
标头的值来执行此操作.如果对您的应用程序的请求是通过HTTPS发出的,则它将设置为https
.您可以在文档这里.
You will probably have to do it on application level by inspecting the value of the X-Forwarded-Proto
header. It will be set to https
if the request to your app came by HTTPS. You can find more info on environment-provided headers in Flexible environment in the docs here.