代码之家  ›  专栏  ›  技术社区  ›  Henry Woody

在Google App Engine Flexible with Django上将http永久重定向到https

  •  1
  • Henry Woody  · 技术社区  · 7 年前

    我正在使用Django,在Python 3灵活的环境中使用Google云平台的App引擎,并尝试将所有请求永久重定向到 http https 所有路线,但迄今为止都没有成功。我可以通过

    我看过这篇文章: How to permanently redirect `http://` and `www.` URLs to `https://`?

    除了重定向之外,该应用程序在各个方面都正常工作。这是我的 app.yaml 文件:

    # [START runtime]
    runtime: python
    env: flex
    entrypoint: gunicorn -b :$PORT myproject.wsgi
    
    runtime_config:
      python_version: 3
    # [END runtime]
    

    myproject/settings.py

    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 ,我被重定向到 https协议 http

    是否有什么我遗漏或做错了,导致重定向没有发生?

    3 回复  |  直到 7 年前
        1
  •  3
  •   Mikhail Burshteyn    7 年前

    设置 secure 在应用程序yaml仅适用于GAE标准但不灵活。这个 app.yaml docs for Flexible 别提这把钥匙。

    您可能需要在应用程序级别检查 X-Forwarded-Proto https here .

        2
  •  1
  •   GAEfan    7 年前

    确保你有 SecurityMiddleware CommonMiddleware 启用,并分配 Base_URL :

    settings.py :

    MIDDLEWARE_CLASSES = (
        ...
        'django.middleware.security.SecurityMiddleware'
        'django.middleware.common.CommonMiddleware',    
    )
    
    BASE_URL = 'https://www.example.com'
    

    或者,您可以编写自己的中间件:

    MIDDLEWARE_CLASSES = (
        ...
        'core.my_middleware.ForceHttps',
    )
    
    BASE_URL = 'https://www.example.com'
    

    my_middleware.py :

    from django.http import HttpResponsePermanentRedirect
    
    class ForceHttps(object):
    
        def process_request(self, request):
    
            if not (request.META.get('HTTPS') == 'on' and settings. BASE_URL == 'https://' + request.META.get('HTTP_HOST') ):
                return HttpResponsePermanentRedirect(settings. BASE_URL + request.META.get('PATH_INFO'))
            else:
                return None
    
        3
  •  1
  •   Dustin Ingram    7 年前

    问题是标题名。当通过WSGI服务器访问Django时,应该使用 X-Forwarded-Proto 标题而不是 HTTP_X_FORWARDED_PROTO .

    见: Why does django ignore HTTP_X_FORWARDED_PROTO from the wire but not in tests?

        4
  •  1
  •   soupcoder    6 年前

    经过反复试验,我发现设置.py将允许的主机更新到适当的域会得到所需的结果:

    ALLOWED_HOSTS = ['https://{your-project-name}.appspot.com','https://www.yourcustomdomain.com'] 
    

    更新:我不再确定上述原因,因为在随后的部署中,上述内容被拒绝,我收到了主机错误。然而,重定向仍然存在。。。:(