前言
Nginx(发音 “Engine-X”)是一款高性能的 HTTP 和反向代理服务器。它以占用内存少、并发能力强、配置灵活著称,国内几乎所有互联网公司都在使用。
本文从核心场景出发,带你掌握 Nginx 最实用的功能。
Nginx 能做什么?
| 场景 |
说明 |
| 🏠 静态网站托管 |
托管 HTML/CSS/JS 文件 |
| 🔄 反向代理 |
隐藏后端服务,统一入口 |
| ⚖️ 负载均衡 |
将请求分发到多台服务器 |
| 🔒 HTTPS 配置 |
SSL/TLS 证书配置 |
| 📦 静态资源缓存 |
CSS/JS/图片缓存优化 |
| 🛡️ 安全防护 |
限流、防盗链、IP 黑白名单 |
一、安装与基础命令
1 2 3 4 5 6 7 8
| sudo apt install nginx
sudo yum install nginx
brew install nginx
|
常用命令:
1 2 3 4 5 6 7 8
| nginx -v nginx -t sudo nginx -s reload sudo nginx -s stop sudo nginx -s quit sudo systemctl start nginx sudo systemctl enable nginx sudo systemctl status nginx
|
二、配置文件结构
1 2 3 4 5 6
| /etc/nginx/nginx.conf
/etc/nginx/sites-available/ /etc/nginx/sites-enabled/
|
最小 nginx.conf:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| worker_processes auto;
events { worker_connections 1024; }
http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" '; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 65; include /etc/nginx/sites-enabled/*; }
|
三、静态网站托管
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 blog.iot2045.cn; root /var/www/blog; index index.html index.htm; access_log /var/log/nginx/blog_access.log; error_log /var/log/nginx/blog_error.log; location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ { expires 30d; add_header Cache-Control "public, immutable"; } location / { try_files $uri $uri/ /index.html; } location ~ /\. { deny all; } }
|
启用站点:
1 2
| sudo ln -s /etc/nginx/sites-available/blog /etc/nginx/sites-enabled/ sudo nginx -t && sudo nginx -s reload
|
四、反向代理(最核心功能)⭐
反向代理让 Nginx 作为前端网关,将请求转发给后端应用。
1
| 用户 → Nginx (80/443) → 后端应用 (3000)
|
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://127.0.0.1:3000; proxy_http_version 1.1; 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_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_connect_timeout 60s; proxy_read_timeout 60s; proxy_send_timeout 60s; proxy_buffering on; proxy_buffer_size 4k; } location /api { proxy_pass http://127.0.0.1:8080; include proxy_params; } }
|
多服务代理示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| server { listen 80; server_name mysite.com; location / { proxy_pass http://127.0.0.1:3000; } location /api { proxy_pass http://127.0.0.1:8080; } location /files { proxy_pass http://127.0.0.1:9000; } }
|
五、负载均衡
将请求分发到多个后端服务器,提高可用性和吞吐量。
5.1 基础配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
server { listen 80; server_name api.example.com; location / { proxy_pass http://backend; } }
|
5.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
| upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; }
upstream backend { server 192.168.1.10:8080 weight=3; server 192.168.1.11:8080 weight=2; }
upstream backend { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; }
upstream backend { least_conn; server 192.168.1.10:8080; server 192.168.1.11:8080; }
upstream backend { server 192.168.1.10:8080 max_fails=3 fail_timeout=30s; server 192.168.1.11:8080 max_fails=3 fail_timeout=30s; server 192.168.1.12:8080 backup; server 192.168.1.13:8080 down; }
|
六、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
| server { listen 443 ssl http2; server_name blog.iot2045.cn; ssl_certificate /etc/nginx/ssl/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_stapling on; ssl_stapling_verify on; root /var/www/blog; index index.html; }
server { listen 80; server_name blog.iot2045.cn; return 301 https://$server_name$request_uri; }
|
💡 免费 SSL 证书推荐使用 Let’s Encrypt + Certbot 自动签发和续期。
七、性能优化
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
| gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml;
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; }
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
location /login { limit_req zone=one burst=20 nodelay; proxy_pass http://backend; }
limit_conn_zone $binary_remote_addr zone=addr:10m;
server { limit_conn addr 10; }
sendfile on; tcp_nopush on; tcp_nodelay on;
|
八、实用配置片段
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
| location ~* \.(jpg|png|gif)$ { valid_referers none blocked blog.iot2045.cn *.iot2045.cn; if ($invalid_referer) { return 403; } }
location /admin { allow 192.168.1.0/24; allow 10.0.0.100; deny all; }
error_page 404 /404.html; error_page 500 502 503 504 /50x.html;
location /api { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS'; add_header Access-Control-Allow-Headers 'Content-Type, Authorization'; if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://backend; }
location /old-page { rewrite ^/old-page(.*)$ /new-page$1 permanent; }
|
九、完整生产环境配置
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
| upstream app_backend { least_conn; server 127.0.0.1:3001 weight=3 max_fails=2 fail_timeout=15s; server 127.0.0.1:3002 weight=2 max_fails=2 fail_timeout=15s; keepalive 32; }
server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }
server { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; root /var/www/app; index index.html; access_log /var/log/nginx/app_access.log; error_log /var/log/nginx/app_error.log; gzip on; gzip_types text/plain text/css application/json application/javascript; gzip_min_length 1024; client_max_body_size 10m; location ~* \.(css|js|jpg|png|gif|ico|svg|woff2)$ { expires 30d; add_header Cache-Control "public"; } location /api { proxy_pass http://app_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; } location / { try_files $uri $uri/ /index.html; } }
|
常见故障排查
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| nginx -t
sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/log/nginx/access.log
sudo ss -tlnp | grep :80
sudo systemctl status nginx
|
结语
Nginx 是现代 Web 架构的核心组件,掌握它能帮你从容应对绝大多数部署场景:
- 个人项目:静态网站 + 反向代理足够
- 中型项目:加上负载均衡和缓存优化
- 大型项目:配合 CDN、微服务网关
Nginx 就像瑞士军刀——功能多但每个都很实用。从静态网站开始,逐步解锁新技能。⚙️