使用 NGINX 将 HTTPS 请求代理到 HTTP 后端

使用 NGINX 将 HTTPS 请求代理到 HTTP 后端

我已将 nginx 配置为我的外部可见的 Web 服务器,它通过 HTTP 与后端通信。

我想要实现的场景是:

  1. 客户端向 nginx 发出 HTTP 请求,该请求重定向到相同的 URL,但通过 HTTPS
  2. nginx 代理通过 HTTP 向后端发送请求
  3. nginx 通过 HTTP 从后端接收响应。
  4. nginx 通过 HTTPS 将其传回给客户端

我当前的配置(后端配置正确)是:

服务器 {
        听80;
        服务器名称本地主机;

        位置 ~ .* {
            代理密码 http://后端;
            代理重定向 http://后端 https://$主机;
            proxy_set_header 主机 $host;
            }
        }

我的问题是,对客户端的响应(步骤 4)是通过 HTTP 而不是 HTTPS 发送的。有什么想法吗?

答案1

您尝试设置的代理类型称为反向代理。快速搜索反向代理 nginx 后,我找到了此页面:

http://intranation.com/entries/2008/09/using-nginx-reverse-proxy/

除了添加一些有用的功能(如 X-Forwarded-For 标头,可让您的应用查看实际的源 IP)之外,它还特别具有以下功能:

proxy_redirect off

祝你好运! :)

答案2

我在生产中使用以下配置

server {
    listen xxx.xxx.xxx.xxx:80;
    server_name www.example.net;

    rewrite ^(.*) https://$server_name$1 permanent;
}

server {
    listen xxx.xxx.xxx.xxx:443;
    server_name www.example.net;

    root   /vhosts/www.example.net;

    ssl                  on;
    ssl_certificate      /etc/pki/nginx/www.example.net.crt;
    ssl_certificate_key  /etc/pki/nginx/www.example.net.key;

    ssl_prefer_server_ciphers on;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
    ssl_dhparam /etc/pki/nginx/dh2048.pem;

    # intermediate configuration. tweak to your needs.
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';

    location / {
        proxy_pass http://127.0.0.1:8080;
        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 https;
    }
}

答案3

server {

    listen 80;
    server_name www.example.net example.net;

   rewrite ^/(.*)$ https://$host$request_uri? permanent; 
}

server {
  listen 443;
  server_name www.example.net example.net;
  .....................

相关内容