📜  将 gunicor 端口更改为 https - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:39:12.359000             🧑  作者: Mango

将 Gunicorn 端口更改为 HTTPS

Gunicorn 是一个 Python WSGI HTTP 服务器,用于在生产环境中部署 Django,Flask 等 Web 应用程序。默认情况下,Gunicorn 使用 HTTP 协议进行通信,如果您希望通过 HTTPS 提供安全的 Web 服务,则需要将 Gunicorn 端口更改为 HTTPS。

前提条件

在更改 Gunicorn 端口之前,确保已经生成了 SSL 证书。您可以购买商业 SSL 证书,也可以使用免费的 SSL 证书,例如 Let's Encrypt

您还需要在服务器上安装 Nginx,因为 Nginx 通常用作反向代理,将 HTTPS 流量路由到 Gunicorn 服务器。

步骤

以下是将 Gunicorn 端口更改为 HTTPS 的步骤:

  1. 在 Gunicorn 服务器上启用 SSL

    确保 Gunicorn 服务器已经安装 SSL 证书,并且将它们的文件路径和密码(如果有)记录在环境变量中:

    export SSL_CERT_PATH=/path/to/ssl_cert.pem
    export SSL_KEY_PATH=/path/to/ssl_key.pem
    export SSL_PASSWORD=your_password
    
  2. 更改 Gunicorn 配置文件

    编辑 Gunicorn 的配置文件,通常是 gunicorn.conf.pygunicorn.conf。在该文件中,您需要更改以下设置:

    bind = '0.0.0.0:8000'
    

    更改为:

    bind = '0.0.0.0:443'
    keyfile = os.environ.get('SSL_KEY_PATH', None)
    certfile = os.environ.get('SSL_CERT_PATH', None)
    ssl_password = os.environ.get('SSL_PASSWORD', None)
    if keyfile and certfile:
        bind += f"?keyfile={keyfile}&certfile={certfile}"
        if ssl_password:
           bind += f"&ssl_password={ssl_password}"
    

    这里将 Gunicorn 的绑定端口更改为 443,它是 HTTPS 的默认端口。然后,使用环境变量中的 SSL 证书设置 keyfilecertfile,并选择是否为 SSL 证书提供密码。最后,将 keyfilecertfile 作为查询字符串添加到绑定位置。

  3. 重新启动 Gunicorn

    您应该重新启动 Gunicorn 服务器以使更改生效:

    sudo systemctl restart gunicorn
    
  4. 更新 Nginx 配置文件

    最后,在 Nginx 配置文件中,将反向代理服务器的位置更改为指向 Gunicorn 使用的新 HTTPS 端口:

    location / {
       proxy_pass http://127.0.0.1:443;
       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_pass 设置中,更改端口为 Gunicorn 使用的 HTTPS 端口(在本例中为 443)。

    然后,重新加载 Nginx:

    sudo systemctl reload nginx
    
结论

现在您已经成功地将 Gunicorn 端口更改为 HTTPS。您的 Web 应用程序现在在安全的 HTTPS 连接上运行,并受到 SSL/TLS 的保护。