Nginx反代配置

安装 Nginx(如果还没装)

1
2
sudo apt update
sudo apt install nginx

配置conf文件

/etc/nginx/sites-available/ 下建一个配置文件 api.example.com.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
listen 80;
server_name api.example.com;

# 日志可选
access_log /var/log/nginx/api.access.log;
error_log /var/log/nginx/api.error.log;

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

# 可选优化
proxy_read_timeout 90;
proxy_connect_timeout 90;
}
}

启动应用并重载

1
2
3
sudo ln -s /etc/nginx/sites-available/api.example.com.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

域名解析(A 记录)

在你的域名服务商(阿里云/DNSPod/Cloudflare 等)里,给 api.example.comwww.api.example.com 分别添加或确认已有的 A 记录,将它们指向你服务器的公网 IP。

配置acme申请https证书

在线安装:

1
sudo curl https://get.acme.sh | sh -s email=my@example.com

nginx的conf中添加如下配置:

1
2
3
4
5
root /home/wwwroot/api.example.com;

location /.well-known/acme-challenge/ {
try_files $uri =404;
}

配置完成后重载:

1
sudo nginx -t && sudo systemctl reload nginx

执行证书申请命令:

1
2
3
acme.sh --issue \
-d example.com -d www.example.com \
--webroot /home/wwwroot/example.com/

如果出现retryafter=86400,则需要切换Let’s Encrypt:

1
2
3
4
5
6
7
# 把默认 CA 改为 Let’s Encrypt
acme.sh --set-default-ca --server letsencrypt

# 然后再申请
acme.sh --issue \
-d example.com -d www.example.com \
--webroot /home/wwwroot/example.com/

验证dns解析的ip是否正确:

1
dig +short example.com

最后完整的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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# —— HTTP:将所有请求重定向到 HTTPS(可选,但强烈推荐)
server {
listen 80;
server_name example.com www.example.com;

# 直接把所有流量走 HTTPS
return 301 https://$host$request_uri;
}

# —— HTTPS 主块
server {
listen 443 ssl http2;
server_name example.com www.example.com;

# 指定你的证书和私钥(用 fullchain 更保险)
ssl_certificate /root/.acme.sh/example.com_ecc/fullchain.cer;
ssl_certificate_key /root/.acme.sh/example.com_ecc/example.com.key;

# 推荐开启的基础安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;

root /home/wwwroot/example.net;

# acme-challenge 保持可访问(续签时需要)
location /.well-known/acme-challenge/ {
alias /home/wwwroot/example.com/.well-known/acme-challenge/;
try_files $uri =404;
}

# 反向代理到你的 59001 服务
location / {
proxy_pass http://10.11.10.101:9001;
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;

proxy_read_timeout 90;
proxy_connect_timeout 90;
}
}

最后再执行重载:

1
sudo nginx -t && sudo systemctl reload nginx