一、Nginx是什么?
Nginx是一个高性能的HTTP服务器和反向代理服务器,以高并发、低内存占用著称。
1.1 Nginx能做什么?
| 功能 |
说明 |
| HTTP服务器 |
静态文件服务、Vue/React前端部署 |
| 反向代理 |
隐藏后端服务、负载均衡 |
| SSL/TLS |
HTTPS支持 |
| 静态资源缓存 |
加速资源访问 |
| 限流 |
防止DDoS攻击 |
| gzip压缩 |
减少传输体积 |
1.2 Nginx vs Apache
| 特性 |
Nginx |
Apache |
| 性能 |
高并发强 |
一般 |
| 内存占用 |
低 |
较高 |
| 配置文件 |
简洁 |
复杂 |
| 异步非阻塞 |
是 |
否 |
| 动态模块 |
不支持 |
支持 |
二、安装Nginx
2.1 Ubuntu/Debian安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| sudo apt update
sudo apt install -y nginx
sudo systemctl start nginx sudo systemctl enable nginx
sudo systemctl status nginx
curl http://localhost
|
2.2 Docker安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| docker pull nginx:alpine
docker run -d \ --name nginx-server \ -p 80:80 \ -v ~/nginx/html:/usr/share/nginx/html \ nginx:alpine
docker run -d \ --name nginx-server \ -p 80:80 \ -v ~/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \ -v ~/nginx/html:/usr/share/nginx/html \ nginx:alpine
|
2.3 目录结构
1 2 3 4 5 6 7 8 9 10 11 12
| /etc/nginx/ ├── nginx.conf ├── conf.d/ ├── sites-available/ ├── sites-enabled/ └── logs/ ├── access.log └── error.log
/usr/share/nginx/html/ /var/log/nginx/
|
三、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 35 36 37
| user www-data; worker_processes auto; pid /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; error_log /var/log/nginx/error.log;
sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048;
gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
include /etc/nginx/conf.d/*.conf; }
|
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
|
server { listen 80; server_name example.com www.example.com;
root /var/www/html; index index.html index.htm;
access_log /var/log/nginx/example_access.log; error_log /var/log/nginx/example_error.log;
location / { try_files $uri $uri/ /index.html; }
error_page 404 /404.html; error_page 500 502 503 504 /50x.html;
location ~ /\. { deny all; access_log off; log_not_found off; } }
|
四、反向代理配置
4.1 什么是反向代理?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| ┌─────────────────────────────────────────────────────────────────┐ │ 正向代理(VPN) │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ 用户 → 代理服务器 → 目标网站 │ │ (客户端知道代理) │ │ │ └─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐ │ 反向代理 │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ 用户 → Nginx反向代理 → 后端服务器1 │ │ ↘ → 后端服务器2 │ │ ↘ → 后端服务器3 │ │ │ │ (用户不知道后端服务器存在) │ │ │ └─────────────────────────────────────────────────────────────────┘
|
4.2 基础反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| server { listen 80; server_name api.example.com;
location / { proxy_pass http://127.0.0.1:8080; 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; } }
|
4.3 代理到多个后端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| upstream backend { server 127.0.0.1:8080 weight=3; server 127.0.0.1:8081 weight=1; server 127.0.0.1:8082 backup; }
server { listen 80; server_name api.example.com;
location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
|
4.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
| upstream roundRobin { server 127.0.0.1:8080; server 127.0.0.1:8081; }
upstream weighted { server 127.0.0.1:8080 weight=5; server 127.0.0.1:8081 weight=1; }
upstream ipHash { ip_hash; server 127.0.0.1:8080; server 127.0.0.1:8081; }
upstream leastConn { least_conn; server 127.0.0.1:8080; server 127.0.0.1:8081; }
|
五、HTTPS配置
5.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 26 27 28 29 30 31 32 33 34 35 36
| server { listen 80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; }
server { listen 443 ssl http2; server_name example.com www.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-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; ssl_prefer_server_ciphers off; add_header Strict-Transport-Security "max-age=31536000" always;
ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s;
root /var/www/html; index index.html;
location / { try_files $uri $uri/ /index.html; } }
|
5.2 免费SSL证书(Let’s Encrypt)
1 2 3 4 5 6 7 8
| sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run
|
六、静态资源优化
6.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
| server { listen 80; server_name static.example.com; root /var/www/static;
location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ { expires 1y; add_header Cache-Control "public, no-transform"; }
location ~* \.(css|js)$ { expires 30d; add_header Cache-Control "public"; }
location ~* \.(woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public"; }
access_log off; }
|
6.2 gzip压缩
1 2 3 4 5 6 7 8
| http { gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_min_length 1024; gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+image/svg+xml; }
|
6.3 防盗链
1 2 3 4 5 6 7 8 9
| location ~* \.(jpg|jpeg|png|gif|ico|mp4|mp3)$ { valid_referers none blocked example.com www.example.com; if ($invalid_referer) { return 403; } }
|
七、实战案例
7.1 Vue/React前端部署
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
| server { listen 80; server_name www.example.com; root /var/www/dist; index index.html;
location / { try_files $uri $uri/ /index.html; }
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ { expires 30d; add_header Cache-Control "public, immutable"; }
location ~ /\. { deny all; }
access_log /var/log/nginx/vue_access.log; error_log /var/log/nginx/vue_error.log; }
|
7.2 Node.js API代理
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 example.com; root /var/www/dist;
location / { try_files $uri $uri/ /index.html; } }
server { listen 80; server_name api.example.com;
location / { proxy_pass http://127.0.0.1:3000; 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_cache_bypass $http_upgrade; } }
|
7.3 多个子域名配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| server { listen 80; server_name example.com www.example.com; root /var/www/html; }
server { listen 80; server_name blog.example.com; root /var/www/blog; }
server { listen 80; server_name api.example.com; root /var/www/api; }
|
7.4 WebSocket代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| upstream websocket { server 127.0.0.1:8080; }
server { listen 80; server_name ws.example.com;
location / { proxy_pass http://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_read_timeout 86400; } }
|
7.5 限流配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server { location /api/ { limit_req zone=api_limit burst=20 nodelay; proxy_pass http://127.0.0.1:8080; } }
limit_conn_zone $binary_remote_addr zone=addr_limit:10m;
server { location / { limit_conn addr_limit 10; } }
|
八、常用命令
8.1 Nginx命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| sudo nginx -t
sudo nginx -s reload
sudo nginx -s stop
sudo nginx -s quit
sudo systemctl restart nginx
ps aux | grep nginx
tail -f /var/log/nginx/access.log tail -f /var/log/nginx/error.log
|
8.2 日志分析
1 2 3 4 5 6 7 8 9 10 11
| awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
awk '{sum+=$10} END {print sum/1024/1024 " MB"}' /var/log/nginx/access.log
|
九、常见问题
9.1 403 Forbidden
1 2 3 4 5 6 7 8 9 10
|
sudo chmod -R 755 /var/www/html sudo chown -R www-data:www-data /var/www/html
index index.html index.htm;
setsebool -P httpd_read_user_content 1
|
9.2 502 Bad Gateway
1 2 3 4 5 6 7
|
ps aux | grep node
netstat -tlnp | grep 8080
tail -f /var/log/nginx/error.log
|
9.3 413 Request Entity Too Large
1 2
| client_max_body_size 20M;
|
十、性能优化建议
| 优化项 |
配置 |
说明 |
| worker进程数 |
worker_processes auto; |
设为CPU核心数 |
| 连接数 |
worker_connections 4096; |
提高并发 |
| 打开文件数 |
worker_rlimit_nofile 65535; |
避免too many open files |
| TCP优化 |
tcp_nopush on; tcp_nodelay on; |
减少网络延迟 |
| 缓存 |
open_file_cache max=65535; |
缓存文件元数据 |
| 压缩 |
gzip on; |
减少传输体积 |
| 静态资源 |
启用缓存 |
减少重复请求 |
参考资料
持续更新中…欢迎收藏!
#Nginx #反向代理 #负载均衡 #Web服务器 #教程