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 而不是上游服务器的路径
相关推荐
.柒宇.5 小时前
nginx入门教程
运维·nginx
cheems952712 小时前
[SpringMVC]Cookie 和Session 从无状态协议到状态保存实务
网络·http
听到微笑16 小时前
MCP传输协议演进:从SSE到Streamable HTTP
网络·网络协议·http
如来神掌十八式16 小时前
nginx + spring gateway+spring 服务_nginx 转发到 gateway
nginx·spring·gateway
hotlinhao16 小时前
Nginx rewrite last 与 redirect 的区别——Vue history 模式短链接踩坑记录
前端·vue.js·nginx
chxii17 小时前
在IIS中开启http跳转到https 和 http2的介绍
前端·http·https
kevien_G118 小时前
Http协议
网络·网络协议·http
handsomestWei1 天前
Docker引擎API接入配置
运维·http·docker·容器·api
tryCbest2 天前
Nginx常用操作命令-Linux和Windows系统
linux·windows·nginx
大數據精準工單獲取2 天前
【数据抓取】 编写爬虫基本请求:使用爬虫框架发送 HTTP 请求,获取网页内容
爬虫·网络协议·http