nginx配置http转发https请求(http接口转发或者代理https接口)

1.需求场景

nginx中代理http的接口一搜一大把,但是利用nginx代理https开头的接口却是很少,大部分都是一些重定向操作,实际使用不了,经过很多次尝试终于解决,可以将https的接口代理到http中为前端提供服务;

2.nginx配置

2.1.代码

shell 复制代码
    server {
        listen       0.0.0.0:8080;
        server_name  localhost;
        # ...
       
        # 前端
        location / {
            root   /xxx/dist;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }

        # 后端
        location /prod-api/ {
            proxy_pass http://127.0.0.1:8081/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        # 第三方https接口请求
        # 请求http://localhost:8080/3rd/api
        # 等于https://www.3rd.com/api
        location /3rd/ {
            proxy_pass https://www.3rd.com/;
            proxy_ssl_verify off;
            proxy_set_header Host www.3rd.com;
            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;

            proxy_redirect https://www.3rd.com/ /;
        }
        # ...
}

2.2.配置说明

配置项 解释
www.3rd.com 只是个示例域名,实际情况根据自己的需求改动
location /3rd/ 这表示该配置块将应用于以 /3rd/开头的所有请求
proxy_pass https://www.3rd.com/ 这告诉Nginx将匹配的请求代理到 https://www.3rd.com/
proxy_ssl_verify off 表示Nginx在代理请求到上游服务器时不会验证SSL证书
proxy_set_header Host jiutian.10086.cn 设置代理请求的 Host 头信息为 www.3rd.com
proxy_set_header X-Real-IP $remote_addr 设置代理请求的 X-Real-IP 头信息为客户端的IP地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for 设置代理请求的 X-Forwarded-For 头信息
proxy_set_header X-Forwarded-Proto $scheme 设置代理请求的 X-Forwarded-Proto 头信息为原始请求的协议(http 或 https)
proxy_redirect https://www.3rd.com/ / 修改上游服务器返回的 Location 头信,当上游服务器返回一个重定向响应时(例如301或302),proxy_redirect 会将 Location 头中的原始URL(https://www.3rd.com/)替换为相对路径(/)。这意味着如果上游服务器返回一个指向 https://www.3rd.com/somepath 的重定向,客户端实际上将被重定向到 /jiutian/somepath 而不是上游服务器的路径
相关推荐
天宇&嘘月18 分钟前
Nginx的https搭建
网络·nginx·https
rainmanqqst19 分钟前
C#Netcore支持Https
网络协议·http·https·c#
rising start3 小时前
三、FastAPI :POST 请求、用户接口设计与 Requests 测试
python·网络协议·http·fastapi
wadesir4 小时前
Nginx负载均衡代理协议详解(从零开始搭建高可用Web服务)
前端·nginx·负载均衡
w***4246 小时前
准确-NGINX 1.26.2配置正向代理并编译安装的完整过程
运维·nginx
b***59436 小时前
在 Ubuntu 22.04 上安装和配置 Nginx 的完整指南
linux·nginx·ubuntu
神秘的土鸡7 小时前
Linux中使用Docker构建Nginx容器完整教程
linux·nginx·docker
i***51267 小时前
Failed to restart nginx.service Unit nginx.service not found
运维·nginx
b***59437 小时前
【Nginx 】Nginx 部署前端 vue 项目
前端·vue.js·nginx