【问题标题】:Redirect http to https flask + appengine将 http 重定向到 https flask + appengine
【发布时间】:2019-03-24 14:56:23
【问题描述】:

我有一个在谷歌应用引擎上运行的网站,它有一个私有的 dns。

但是每次我打开该网站时,它都会以 http 形式打开,我尝试在烧瓶上使用 before_request 装饰器将 http 更改为 https,但我得到了 too_many_redirects 错误,我也尝试使用 ProxyFix 但由于我的页面没有 X-Forwarded -Proto 作为标题,它不会重定向到正确的页面。

编辑:我忘了说我使用的是 flex 环境

配置此行为的最佳方式是什么?我在哪里可以设置此配置,如果可能,我该如何设置?

这就是我尝试重定向的方式:

@app.before_request
def before_request():
    if request.endpoint in app.view_functions and request.headers.get('X-Forwarded-Proto', None) == 'http':
        code = 301
        return redirect(request.url.replace('http://', 'https://'), code=code)

非常感谢您的帮助!

【问题讨论】:

    标签: python google-app-engine flask


    【解决方案1】:

    您可以使用以下方法更直接地检查https

    if request.environ.get('HTTPS') == 'off':
        return redirect(...)
    

    甚至:

    if not request.is_secure:
        return redirect(...)
    

    但您还必须处理不希望重定向的时间(本地主机、版本、cron 作业等)。开始:

    #so can test versions, don't redirect appspot urls:
    if "appspot" in request.environ.get('HTTP_HOST'):
        return None
    
    if os.environ['SERVER_NAME'].startswith('1') or os.environ['SERVER_NAME'].startswith('localhost'):
        return None
    
    user_agent = request.environ.get('HTTP_USER_AGENT', 'fake')
    
    # cron, taskqueue, module, development, no redirect
    if (    'AppEngine-Google' in user_agent or 
            'my-module' in request.environ.get('CURRENT_MODULE_ID')):
        return None
    

    【讨论】:

      【解决方案2】:

      看看这个 python flask redirect to https from http

      @app.before_request
      def before_request():
          if request.url.startswith('http://'):
              url = request.url.replace('http://', 'https://', 1)
              code = 301
              return redirect(url, code=code)
      

      【讨论】:

        【解决方案3】:

        由于您使用的是 App Engine,您可能只想更改您的 app.yaml 以始终要求 URL 是安全的。例如:

        - url: .*
          script: main.app
          secure: always
        

        seucre: always 标志确保使用该规则路由的所有请求都被加密。完全不需要 Flask。

        【讨论】:

        • 我忘了说我使用的是弹性环境,所以安全标志不起作用
        • 我明白了。好吧,如果您的代理没有添加 X-Forwarded-Proto,我不确定您可以做些什么来弄清楚如何添加 https。我会说你的代理比 Python 或 Flask 更成问题,因为那时它们不参与。但是,我会尝试制作一个打印出所有请求标头的页面,以查看是否添加了可以使用的内容,而不是 X-Forwarded-Proto
        • 我已经检查了请求标头,并且没有带有 http 或 https 的标头。有没有办法让我查看谷歌的应用引擎代理或编辑以发送 X-Forwarded-Proto 标头?
        【解决方案4】:

        我还在应用引擎上运行烧瓶应用。使用烧瓶护身符并将 force_https_permanent 设置为 true 并将 force_https 设置为 true https://github.com/GoogleCloudPlatform/flask-talisman

        护身符=护身符( 应用程序, content_security_policy=csp, content_security_policy_nonce_in=['script-src'], force_https_permanent='true', force_https='真' )

        上面的示例woold还添加了一个对安全也非常有用的csp。

        【讨论】:

          猜你喜欢
          • 2021-01-01
          • 2013-02-13
          • 2017-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2013-11-05
          相关资源
          最近更新 更多