部署前端项目到 Vercel,生产环境的 VITE_BASE_API 我直接设置的云服务器 IP 地址,结果发现请求报错,F12 查看控制台发现提示不允许未使用 HTTPS 的 API

已知 App Backend 使用 docker 部署在腾讯云服务器上,常用域名托管在 Cloudflare,那我就需要为云服务器设置一个域名,api.kinoko.fun,然后为其配置 SSL 证书

Cloudflare

也没什么好说的,先将域名解析到云服务器 IP

image.png

云服务器配置

云服务器使用的是 Rocky Linux 系统

先安装 Nginx,并启动服务

1
2
3
sudo dnf install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

添加 server 配置

1
sudo vim /etc/nginx/conf.d/api.kinoko.fun.conf

具体配置项自己修改,这里只是个模板,其中 YOUR_DOMAIN 就是你需要配置的域名,PORT是容器暴露的端口

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name YOUR_DOMAIN;

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

验证配置是否正确

1
sudo nginx -t

若没有问题,重启 nginx

1
sudo systemctl restart nginx

然后我们需要配置 HTTPS,按照以下步骤安装 Certbot 并配置 SSL 证书

安装 Cerbot

1
sudo apt install certbot python3-certbot-nginx

获取 SSL 证书并自动配置 Nginx

1
sudo certbot --nginx -d api.kinoko.fun

此时回顾 /etc/nginx/conf.d/api.kinoko.fun.conf 文件,你会发现其内容已经发生变化(已经自动配置了 SSL)

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
server {
server_name api.kinoko.fun;

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

listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.kinoko.fun/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.kinoko.fun/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
if ($host = api.kinoko.fun) {
return 301 https://$host$request_uri;
} # managed by Certbot


listen 80;
server_name api.kinoko.fun;
return 404; # managed by Certbot
}

完成之后访问自己部署的服务即可,记得在腾讯云服务器控制台中开放对应端口 :D