Appearance
Nginx 代理所有 SSL/TLS 并转发二级域名至指定端口
1. /etc/nginx/nginx.conf
这里 /etc/nginx/nginx.conf 的配置基本为 Nginx 的默认配置:
Nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
gzip on;
include /etc/nginx/conf.d/servers.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
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
2. /etc/nginx/conf.d/servers.conf
Nginx
# 1. 将任意域名的 HTTP 请求重定向为 HTTPS
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
# 2. 在 https://www.yourdomain.com 上搭建静态站点
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name www.yourdomain.com;
include /etc/nginx/conf.d/ssl.conf;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
# 3. 将 api.yourdomain.com 的请求转发到 8000 端口
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name api.yourdomain.com;
include /etc/nginx/conf.d/ssl.conf;
location / {
proxy_pass http://localhost:8000;
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;
}
}
# 4. 其余 *.yourdomain.com 二级域名响应 403
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name _;
include /etc/nginx/conf.d/ssl.conf;
return 403;
}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
50
51
52
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
50
51
52
3. /etc/nginx/conf.d/ssl.conf
Nginx
ssl_certificate /path/to/your.pem;
ssl_certificate_key /path/to/your.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:50m;
ssl_session_timeout 24h;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
4. 总结
这里 8000 端口上的服务不需要再配置 SSL。这是因为 Nginx 作为反向代理处理了 HTTPS 请求,并将解密后的流量以 HTTP 形式转发到后台服务。
简单来说,Nginx 负责终止 SSL/TLS 连接,并将流量转换为普通的 HTTP 请求发送给后端服务。所以,后端服务(监听 8000 端口的应用)只需要处理标准的 HTTP 流量,而无需处理 SSL/TLS。
这种配置方式有以下几个优点:
- 简化后端服务配置:后端服务不需要处理 SSL/TLS 证书管理、加解密操作,降低了复杂性;
- 性能优化:SSL/TLS 加解密是计算密集型任务,集中在 Nginx 处理可以减少后端服务器的负载;
- 集中管理证书:所有的 SSL/TLS 证书管理都集中在 Nginx,方便统一配置和更新;
因此,你只需要确保 Nginx 的 SSL 配置正确,后端服务无需配置 SSL。