如何强制 AppEngine 灵活环境中的 Python 3 Django 应用程序始终使用 https?

2024-03-08

当使用带有 Google 生成的安全证书的自定义域时,如何将 http 请求重定向到 https?

我尝试在设置中将 Django 属性 SECURE_SSL_REDIRECT 设置为 True,但这不起作用。

编辑:是的,这个问题已经存在,但该解决方案仅适用于Python2。

解决方案:就我而言,解决方案只是从 Appengine 灵活环境切换到 Appengine 标准环境。我使用以下 app.yaml 解决了 SSL 问题。

runtime: python37
entrypoint: gunicorn -b :$PORT <django-project-name>.wsgi

handlers:
  - url: /.*
    secure: always
    redirect_http_response_code: 301
    script: auto

beta_settings:
  cloud_sql_instances: "<project-id>:<region>:<cloud-sql-instance>"

经过一番猜测和检查,我偶然发现了一个解决方案。

不要使用 SECURE_SSL_REDIRECT Django 设置。相反,更新您的 app.yaml 以包含 secure:always,但还要确保设置了入口点,将 url 设置为 /.*,并将脚本设置为 auto。

尽管 Google 文档明确指出处理程序部分已被弃用,但测试应用程序在使用或不使用处理程序部分部署时发现,截至今天,GAE 确实引用了 app.yaml 的处理程序部分。

编辑:发现这个清楚地显示了 Python 3.7 app.yaml 中的处理程序 -https://cloud.google.com/appengine/docs/standard/python3/config/appref#handlers_element https://cloud.google.com/appengine/docs/standard/python3/config/appref#handlers_element

app.yaml

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT <projectid>.wsgi

handlers:
  - url: /.*
    secure: always
    script: auto

beta_settings:
    cloud_sql_instances: "<projectid>:<dbregion>:<dbinstance>"

runtime_config:
  python_version: 3

在遇到更多问题后,尽管文档说处理程序可以工作,但我已切换到 Appengine 标准环境,并且它运行良好。

runtime: python37
entrypoint: gunicorn -b :$PORT <django-project-name>.wsgi

handlers:
  - url: /.*
    secure: always
    redirect_http_response_code: 301
    script: auto

beta_settings:
  cloud_sql_instances: "<project-id>:<region>:<cloud-sql-instance>"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何强制 AppEngine 灵活环境中的 Python 3 Django 应用程序始终使用 https? 的相关文章

随机推荐