繁体   English   中英

如何使用 Gunicorn 将 http 重定向到 https

[英]How to redirect http to https with Gunicorn

我使用 Flask 作为 Web 应用程序,将 http 重定向到 Z5E056C500A1C48:5Z 中的代码。

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


if __name__ == '__main__':
    app.run()

supervisor.conf 中的 gunicorn 命令是:

command=/home/MyToDo/venv/bin/gunicorn --certfile=/home/MyToDo/SSL/mytodo.vip.cer --keyfile=/home/MyToDo/SSL/mytodo.vip.key -w3 -b0.0.0.0:443 -b0.0.0.0:80 app:app

但是当我访问该网站时,我仍然需要在url前面添加“https://”,它没有自动重定向。 那么如何使gunicorn将http重定向到https,使用Nginx是唯一的方法吗?

我在使用gunicorn的Google App Engine Flexible环境上运行Flask时遇到了相同的问题。 通过使用Werkzeug版本0.14.1的 werkzeug.contrib.fixers.ProxyFix解决。

from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)

app.wsgi_app = ProxyFix(app.wsgi_app)

我在使用 Google App Engine 时遇到了同样的问题,并且在这方面花费了太多时间,因为包括werkzeug.contrib.fixers.ProxyFix和官方文档的自定义HTTPMethodsOverrideMiddleware或其他自定义解决方案在内的所有答案都对我不起作用

我终于设法通过使用以下配置配置gunicorn来解决这个问题:

secure_scheme_headers = {'X-FORWARDED-PROTO': 'https'}
forwarded_allow_ips = '*'

Additionally, for the ones wanting to serve static files and who are struggling with unwanted http redirects, adding handlers for each static directory in the .yaml configuration and avoiding nested sub-directories solved this issue.

烧瓶==2.1.3
独角兽==20.1.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM