第316集Nginx架构实战:反向代理、SSL配置与HTTPS性能优化的高可用Web架构
|字数总计:3.5k|阅读时长:17分钟|阅读量:
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
|
user nginx; worker_processes auto; worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events { worker_connections 10240; use epoll; multi_accept on; }
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; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; client_max_body_size 10m;
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;
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
|
server { listen 80; listen [::]:80; server_name www.example.com example.com; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; return 301 https://$server_name$request_uri; }
server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.example.com example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; 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; 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 / { 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; 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
| server { listen 80; server_name ws.example.com;
location / { proxy_pass http://websocket_backend; 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; 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;
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; }
location /user { rewrite ^/user$ /api/user permanent; }
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
|
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
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
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
| server { listen 443 ssl http2; server_name www.example.com;
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_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; ssl_session_tickets off;
ssl_stapling on; ssl_stapling_verify on; ssl_stapling_file /etc/nginx/ssl/stapling/example.com.ocsp;
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;
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_buffer_size 16k; ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; ssl_session_tickets off; ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers off; ssl_early_data on; server { listen 443 ssl http2; server_name example.com; } }
|
五、高可用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
| 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
|
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 } 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
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; }
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; 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
| user www-data; worker_processes auto; worker_cpu_affinity auto;
error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;
events { worker_connections 4096; use epoll; multi_accept on; }
http { worker_rlimit_nofile 65535;
sendfile on; tcp_nopush on; tcp_nodelay on;
keepalive_timeout 65; keepalive_requests 100;
client_body_buffer_size 128k; client_header_buffer_size 4k; large_client_header_buffers 4 16k;
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; } } }
|
七、安全配置
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;
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|OPTIONS)$) { return 405; }
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 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
|
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; server 192.168.1.20:9090; server 192.168.1.21:9090; server 192.168.1.22:9090; }
server { listen 80; server_name www.example.com; return 301 https://$server_name$request_uri; }
server { listen 443 ssl http2; server_name www.example.com;
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; }
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架构的核心组件。本文介绍了:
核心要点
- 反向代理:隐藏后端、负载均衡、故障转移
- SSL/HTTPS:HTTPS配置、性能优化、安全加固
- 高可用架构:主备切换、Keepalived、健康检查
- 性能优化:缓存、压缩、Worker调优
技术栈
- Web服务器:Nginx
- SSL证书:Let’s Encrypt
- 高可用:Keepalived
- 负载均衡:轮询、加权、一致性哈希
实践建议
- 启用HTTPS并配置HSTS
- 合理配置Worker进程和连接数
- 使用限流保护后端服务
- 部署主备Nginx提高可用性
通过合理的Nginx架构设计,企业可构建高可用、高性能的Web服务。