nginx实现本地http转https请求

「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战

引言

项目中有需要做接口回调,测试和dev环境都是https方式请求调用没有问题,但是本地调试不通。因为本地启动后端服务都是http请求,所以使用nginx代理,将http请求转换为https请求,方便调试。

安装nginx

在上家单位已经安装过nginx,为了写这篇文章又找了一下官网(nginx.org/en/download…),根据自己电脑系统安装。本人电脑是windows。
image.png
下载完成后解压文件,拷贝到不包含中文名的文件夹中,我习惯将软件安装统一放在software文件夹中。
image.png
通过nginx.exe文件或通过命令start nginx启动nginx。启动后访问localhost验证是否启动成功。
image.png

安装OpenSSL

访问官网(slproweb.com/products/Wi…)下载。
image.png
安装到对应文件夹中。

image.png
配置环境变量,配置OPENSSL_HOME

image.png
配置path
image.png

生成https证书

创建ssl文件夹用于存放证书。创建私钥 (建议使用系统窗口,不要用gitBash 有涉及到选择的地方,gitBash无法选择)

1
csharp复制代码openssl genrsa -des3 -out shidian.key 1024 //shidian 自己取的名字

image.png

输入pass作为密码,两次一致。

文件夹中生成shidian.key文件
创建csr证书。

1
vbnet复制代码openssl req -new -key shidian.key -out shidian.csr

image.png
此时有两个文件

image.png
复制 shidian.key 并重命名 shidian.key.org
执行命令

1
vbnet复制代码openssl rsa -in shidian.key.org -out shidian.key

image.png
生成crt证书

1
csharp复制代码openssl x509 -req -days 365 -in shidian.csr -signkey shidian.key -out shidian.crt

最终文件夹的文件为
image.png

修改nginx.conf配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
yml复制代码upstream aglacwy {
server localfop.hanhang.com:11295;
keepalive 64;
}
server {
listen 443 ssl;
server_name localfop.chehejia.com; # 配置的https的域名

ssl_certificate D://software//nginx-1.21.4//ssl//shidian.crt; # 这个是证书的crt文件所在目录
ssl_certificate_key D://software//nginx-1.21.4//ssl//shidian.key; # 这个是证书key文件所在目录

ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;

ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Connection "";
proxy_http_version 1.1;
if ($request_method ~ ^(POST|DELETE|OPTIONS)$) {
proxy_pass http://aglacwy;
break ;
}
proxy_pass http://aglacwy;
}
}

localfop.hanhang.com为本机电脑修改host后的域名,如果需要可以在hosts文件中将localhost配置为想设置的域名
image.png

执行命令nginx -s reload重启nginx。通过https访问接localfop.hanhang.com/test/test/n…,通过断点可通。响应请求结果。

image.png
至此,成功将http请求转化为https请求。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%