Nginx架构实战:反向代理、SSL配置与HTTPS性能优化

一、Nginx基础架构

1.1 Nginx概述

Nginx是高性能的HTTP和反向代理服务器,具有以下特点:

  • 高性能:事件驱动、异步非阻塞架构
  • 高并发:可处理百万级并发连接
  • 低内存占用:相比Apache更轻量
  • 负载均衡:支持多种负载均衡算法
  • 反向代理:隐藏后端服务器
  • SSL/TLS支持:HTTPS配置简单

1.2 Nginx架构设计

核心架构组件

  • Master进程:管理Worker进程
  • Worker进程:处理请求
  • Cache进程:缓存管理
  • SSL模块:HTTPS支持

二、Nginx基础配置

2.1 主配置文件

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# nginx.conf - Nginx主配置文件

# 全局配置
user nginx; # Nginx运行用户
worker_processes auto; # Worker进程数(auto自动检测CPU核心数)
worker_rlimit_nofile 65535; # Worker进程最大打开文件数

# 错误日志
error_log /var/log/nginx/error.log warn;

# PID文件
pid /var/run/nginx.pid;

# 事件模块配置
events {
worker_connections 10240; # 每个Worker进程的最大连接数
use epoll; # 使用epoll事件模型(Linux高效)
multi_accept on; # 允许一个Worker同时接受多个连接
}

# HTTP模块配置
http {
# 基础MIME类型
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; # 启用sendfile零拷贝
tcp_nopush on; # 优化TCP数据传输
tcp_nodelay on; # 禁用TCP Nagle算法
keepalive_timeout 65; # Keep-Alive超时
types_hash_max_size 2048; # 类型哈希表大小
client_max_body_size 10m; # 最大上传文件大小

# Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript
text/xml application/xml application/xml+rss text/javascript;

# 隐藏Nginx版本号
server_tokens off;

# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}

2.2 虚拟主机配置

基础虚拟主机配置

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# /etc/nginx/conf.d/www.example.com.conf

# HTTP配置 - 重定向到HTTPS
server {
listen 80;
listen [::]:80;
server_name www.example.com example.com;

# 添加HSTS响应头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

# 重定向所有请求到HTTPS
return 301 https://$server_name$request_uri;
}

# HTTPS配置
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com example.com;

# SSL证书配置
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

# SSL优化配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;

# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/ssl/chain.crt;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

# 安全响应头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;

# 根目录
root /var/www/example.com;
index index.html index.htm index.php;

# 访问日志
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log warn;

# 主要location配置
location / {
try_files $uri $uri/ /index.html;
}

# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}

# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}

三、Nginx反向代理配置

3.1 基础反向代理

简单反向代理配置

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
# 反向代理到后端应用
server {
listen 80;
server_name api.example.com;

# 反向代理配置
location / {
proxy_pass http://backend_server;

# 代理请求头
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_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 缓冲设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
}

# 后端服务器组
upstream backend_server {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

3.2 高级反向代理配置

负载均衡配置

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
# 负载均衡配置
upstream backend_pool {
# 服务器配置
server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s backup;

# 负载均衡算法
# least_conn; # 最少连接数
# ip_hash; # IP哈希
# hash $request_uri consistent; # 一致性哈希

# Keepalive连接
keepalive 32;
keepalive_timeout 60s;
keepalive_requests 100;
}

server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://backend_pool;

# 代理优化
proxy_http_version 1.1;
proxy_set_header Connection "";

# 请求头设置
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_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 缓冲配置
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 16 8k;
proxy_busy_buffers_size 16k;
proxy_temp_file_write_size 16k;

# 禁用临时文件
proxy_max_temp_file_size 0;
}
}

3.3 WebSocket反向代理

WebSocket配置

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
# WebSocket反向代理配置
server {
listen 80;
server_name ws.example.com;

location / {
proxy_pass http://websocket_backend;

# WebSocket升级
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

# 基本请求头
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;

# WebSocket超时(需要长连接)
proxy_connect_timeout 7d;
proxy_send_timeout 7d;
proxy_read_timeout 7d;
}
}

upstream websocket_backend {
server 192.168.1.20:8080;
server 192.168.1.21:8080;
}

3.4 路径重写代理

路径重写配置

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
# 路径重写代理
server {
listen 80;
server_name api.example.com;

# 代理 /api 到后端 /api
location /api/ {
proxy_pass http://backend_server/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

# 重写路径:/user -> /api/user
location /user {
rewrite ^/user$ /api/user permanent;
}

# 代理并移除 /old 前缀
location /old/ {
rewrite ^/old/(.*)$ /$1 break;
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

四、SSL/HTTPS配置

4.1 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
# 1. 使用Let's Encrypt免费证书
# 安装certbot
sudo apt-get update
sudo apt-get install certbot python3-certbot-nginx

# 申请证书
sudo certbot --nginx -d example.com -d www.example.com

# 证书自动续期
sudo certbot renew --dry-run

# 2. 手动配置证书
# 创建SSL目录
sudo mkdir -p /etc/nginx/ssl

# 复制证书文件
sudo cp example.com.crt /etc/nginx/ssl/
sudo cp example.com.key /etc/nginx/ssl/
sudo chmod 600 /etc/nginx/ssl/example.com.key

# 3. 生成自签名证书(仅用于测试)
sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/nginx/ssl/self-signed.key \
-out /etc/nginx/ssl/self-signed.crt

HTTPS配置优化

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
# HTTPS优化配置
server {
listen 443 ssl http2;
server_name www.example.com;

# SSL证书
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_trusted_certificate /etc/nginx/ssl/chain.crt;

# SSL协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off; # TLS 1.3不需要

# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off; # 禁用session tickets提升安全性

# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_stapling_file /etc/nginx/ssl/stapling/example.com.ocsp;

# HSTS (HTTP Strict Transport Security)
add_header Strict-Transport-Security
"max-age=31536000; includeSubDomains; preload" always;

# 安全响应头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# HTTP/2推送
http2_push_preload on;

# 其他配置...
root /var/www/example.com;
index index.html;

location / {
try_files $uri $uri/ /index.html;
}
}

4.2 SSL性能优化

SSL性能优化配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
http {
# SSL性能优化
ssl_buffer_size 16k; # SSL缓冲区大小

# SSL协议优化
ssl_session_cache shared:SSL:50m;
ssl_session_timeout 1d;
ssl_session_tickets off;

# SSL加密套件优化(PFS前向保密)
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;

# SSL握手优化
ssl_early_data on; # TLS 1.3 0-RTT

server {
listen 443 ssl http2;
server_name example.com;

# 其他HTTPS配置...
}
}

五、高可用Nginx架构

5.1 Nginx集群配置

主备Nginx配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 主Nginx服务器
server {
listen 80;
server_name www.example.com;

# 备份服务器检查
location /nginx-health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}

# 主流量
location / {
proxy_pass http://backend;
}
}

upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}

Keepalived高可用配置

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
# /etc/keepalived/keepalived.conf

global_defs {
router_id nginx-main
}

vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -5
fall 3
rise 2
}

vrrp_instance VI_NGINX {
state MASTER
interface eth0
virtual_router_id 100
priority 100
advert_int 1

authentication {
auth_type PASS
auth_pass nginx-secret
}

virtual_ipaddress {
192.168.1.100 # 虚拟IP
}

track_script {
chk_nginx
}

notify_master "/etc/keepalived/notify_master.sh"
notify_backup "/etc/keepalived/notify_backup.sh"
}
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
# check_nginx.sh - Nginx健康检查

if ! systemctl is-active --quiet nginx; then
exit 1
fi

if ! curl -f http://localhost/nginx-health > /dev/null 2>&1; then
exit 1
fi

exit 0

5.2 限流与防护

Nginx限流配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 限流配置
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=10r/m;
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
limit_req_zone $server_name zone=server_limit:10m rate=1000r/s;

server {
listen 80;
server_name www.example.com;

# 全局限流
limit_req zone=server_limit burst=20 nodelay;

# 登录接口限流
location /api/login {
limit_req zone=login_limit burst=2 nodelay;
proxy_pass http://backend;
}

# API限流
location /api/ {
limit_req zone=api_limit burst=50 nodelay;
proxy_pass http://backend;
}
}

连接数限制

1
2
3
4
5
6
7
8
# 连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_conn_zone $server_name zone=perserver:10m;

server {
limit_conn conn_limit 10; # 每个IP最多10个连接
limit_conn perserver 1000; # 服务器总连接数
}

六、性能优化

6.1 Nginx性能调优

Worker配置优化

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
# nginx.conf
user www-data;
worker_processes auto; # 自动检测CPU核心
worker_cpu_affinity auto; # CPU亲和性

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
worker_connections 4096; # 每个Worker最大连接数
use epoll; # Linux使用epoll
multi_accept on; # 允许一次接受多个连接
}

http {
# 文件描述符优化
worker_rlimit_nofile 65535;

# 系统调用优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;

# Keep-Alive优化
keepalive_timeout 65;
keepalive_requests 100;

# 缓冲优化
client_body_buffer_size 128k;
client_header_buffer_size 4k;
large_client_header_buffers 4 16k;

# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml;

# 其他服务器配置...
}

6.2 缓存配置

Nginx缓存配置

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
# 缓存配置
http {
# 代理缓存路径
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=my_cache:10m
max_size=10g
inactive=60m
use_temp_path=off;

server {
location / {
proxy_pass http://backend;

# 启用缓存
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

# 缓存键
proxy_cache_key "$scheme$request_method$host$request_uri";

# 缓存控制头
add_header X-Cache-Status $upstream_cache_status;

# 绕过缓存
# proxy_cache_bypass $http_pragma $http_authorization;
# proxy_no_cache $http_pragma $http_authorization;
}
}
}

七、安全配置

7.1 Nginx安全加固

安全配置

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
# 安全配置
server {
listen 80;
server_name example.com;

# 隐藏版本号
server_tokens off;

# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|OPTIONS)$) {
return 405;
}

# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;

# 防止XSS攻击
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;

# 防止MIME类型混淆
add_header X-Content-Type-Options "nosniff" always;

# 内容安全策略
add_header Content-Security-Policy
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;

# 限制请求大小
client_max_body_size 10m;
client_body_buffer_size 128k;

# 限制请求速率
limit_req zone=api_limit burst=50 nodelay;

# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}

八、实战案例

8.1 企业级Nginx配置

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 企业级Nginx完整配置
# /etc/nginx/conf.d/enterprise.conf

# 上游服务器组
upstream web_backend {
least_conn; # 最少连接数算法

server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s;

keepalive 64;
}

upstream api_backend {
ip_hash; # IP哈希算法

server 192.168.1.20:9090;
server 192.168.1.21:9090;
server 192.168.1.22:9090;
}

# HTTP服务 - 重定向到HTTPS
server {
listen 80;
server_name www.example.com;

return 301 https://$server_name$request_uri;
}

# HTTPS主服务
server {
listen 443 ssl http2;
server_name www.example.com;

# SSL配置
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# 日志
access_log /var/log/nginx/www.access.log main;
error_log /var/log/nginx/www.error.log warn;

# 根目录
root /var/www/example.com;
index index.html;

# 静态文件
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}

# API代理
location /api/ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";

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_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}

# 主应用
location / {
try_files $uri $uri/ /index.html;
}
}

九、总结

Nginx反向代理是现代化Web架构的核心组件。本文介绍了:

核心要点

  1. 反向代理:隐藏后端、负载均衡、故障转移
  2. SSL/HTTPS:HTTPS配置、性能优化、安全加固
  3. 高可用架构:主备切换、Keepalived、健康检查
  4. 性能优化:缓存、压缩、Worker调优

技术栈

  • Web服务器:Nginx
  • SSL证书:Let’s Encrypt
  • 高可用:Keepalived
  • 负载均衡:轮询、加权、一致性哈希

实践建议

  1. 启用HTTPS并配置HSTS
  2. 合理配置Worker进程和连接数
  3. 使用限流保护后端服务
  4. 部署主备Nginx提高可用性

通过合理的Nginx架构设计,企业可构建高可用、高性能的Web服务。