nginx配置反向代理服务器,实现在https网站中请求http资源

2023-04-20,,

网站使用nginx作为服务器,协议从http升级为https的注意事项。

具体升级步骤请点击搜索

1、首先,修改宝塔面板配置

选择配置文件,http请求重定向为https。所有80端口请求都重定向为https请求

# server代表的是nginx其中的一个服务器
server
{
listen 80; # listen表示监听端口号80 (http)
listen 443 ssl http2; # 表示监听443 端口号(https)
server_name www.abc.com abc.com ip地址; # server_name表示服务器名称,现在同时匹配3个
index index.php index.html index.htm default.php default.htm default.html; # 匹配/www/wwwroot/abc/index.html
root /www/wwwroot/abc; # abc表示路径,网站的起始位置为/www/wwwroot/abc #HTTP_TO_HTTPS_START
if ($server_port !~ 443){ # 端口号不等于443,则重写url到https://当前主机/后面所有路径,并永久重定向(permanent)
rewrite ^(/.*)$ https://$host$1 permanent;
}

2、接着配置代理服务器

# 代理serve图片服务器api
location /api/ {
# 通过代理,访问https://ip|域名/api/...时,代理到http://你的ip或域名:3004/api/...
proxy_pass http://你的ip或域名:3004; # 注意`http://你的ip或域名:3004`末尾不添加`/`,这样的话`/api/`将会添加到3004后面
proxy_redirect off;
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;
} # 代理音乐服务器api
# /musicapi/,必须加上后面的/,不然代理服务不成功
location /musicapi/ {
# 访问https://你的ip或域名/musicapi/...,
# 代理到http://你的ip或域名:3005/...,不包括/musicapi
proxy_pass http://你的ip或域名:3005/; # 这里末尾添加了`/`,将不会添加`/musicapi/`在端口号后面
proxy_redirect off;
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;
}

3、完成上面所有配置后

http网站升级到https网站,浏览器可正常访问网站,网站请求的api接口,需要从http://ip|域名:3005/lyric?id=32507038修改为http(s)://ip|域名/musicapi/lyric?id=32507038。这里的流程就是,把原本请求的:3005/musicapi替换掉,然后浏览器发出并重定向成https开头的请求,接着nginx发现你的请求中带有/musicapi,就把你的请求转发给匹配上的http://你的ip或域名:3005/服务器。

4、最后还要在原来的index.html文件里添加

# 把http链接升级为https
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />

5、或者可以操作服务端的话,也可以在nginx配置里添加

server
{
listen 80;
listen 443 ssl http2;
......
#升级可以升级为https的连接,兼容http
add_header Content-Security-Policy "upgrade-insecure-requests;connect-src *";
}

参考nginx中文配置

nginx配置反向代理服务器,实现在https网站中请求http资源的相关教程结束。

《nginx配置反向代理服务器,实现在https网站中请求http资源.doc》

下载本文的Word格式文档,以方便收藏与打印。