【问题标题】:Flask url_for generates http instead of https when running by dockerFlask url_for 由 docker 运行时生成 http 而不是 https
【发布时间】:2018-07-11 13:57:53
【问题描述】:

我有一个在 docker 中运行的烧瓶应用程序,并使用 Let's Encrypt 设置 nginx。我已将 proxy_set_header X-Forwarded-Proto $scheme; 添加到我的 nginx 配置中,但 url_for 仍然返回 http url 而不是 https url。但是这个问题只有在docker中运行时才会出现。

这是我的 nginx 配置:

server {
    listen 443 ssl default_server;
    ssl_certificate /etc/letsencrypt/live/markote.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/markote.app/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

还有我的 docker 文件:

FROM python:3.6-slim

WORKDIR /app

ADD . /app

RUN apt update
RUN apt install -y curl sudo gnupg libcairo2-dev
RUN pip install gunicorn
RUN curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
RUN sudo apt-get install -y nodejs

RUN python setup.py install
RUN npm install
RUN npm run build

EXPOSE 5000

CMD [ "gunicorn", "-c", "gunicorn.py", "wsgi:app" ]

如果我运行gunicorn -c gunicorn.py wsgi:app & 而不是sudo docker run -d -p 5000:5000 my/repourl_for 可以成功生成https。我错过了什么吗?

【问题讨论】:

    标签: docker nginx flask


    【解决方案1】:

    我知道已经有一段时间了,但你可以试试url_for('endpoint', _schema='https')

    【讨论】:

    • 我试试看。谢谢!
    • 我刚刚找到了另一个解决方案。 _schema 属性仅适用于单个链接,但是,如果您不想对每个 url 都这样做,您可以创建一个设置 wsgi.url_scheme 属性的 wsgi 中间件。看看这个 sn-p 以了解如何做到这一点:flask.pocoo.org/snippets/35 只需确保在中间件的 __call__ 函数中添加类似 environ['wsgi.url_scheme'] = 'https' 的内容。
    猜你喜欢
    • 2013-01-26
    • 2022-12-18
    • 1970-01-01
    • 2022-10-31
    • 2016-10-17
    • 2023-02-24
    • 2019-05-29
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多