Nginx 学习笔记
一、Nginx 简介
Nginx (engine x) 是一个高性能的 HTTP 和反向代理 web 服务器,同时也提供了 IMAP/POP3/SMTP 服务。其特点是占有内存少,并发能力强,事实上 nginx 的并发能力确实在同类型的网页服务器中表现较好。
1.1 主要特性
- 高并发处理:采用事件驱动架构,能够处理数万个并发连接
- 低内存消耗:内存占用小,10,000 个非活跃的 HTTP keep-alive 连接仅占用约 2.5MB 内存
- 负载均衡:支持多种负载均衡算法
- 反向代理:强大的反向代理功能,支持缓存、SSL 等
- 热部署:支持热加载,无需中断服务即可更新配置
1.2 应用场景
- Web 服务器
- 反向代理服务器
- 负载均衡器
- API 网关
- 静态资源服务器
- WebSocket 代理
二、Nginx 安装
2.1 Ubuntu/Debian 安装
1 2
| sudo apt update sudo apt install nginx
|
2.2 CentOS/RHEL 安装
1 2
| sudo yum install epel-release sudo yum install nginx
|
2.3 从源码安装
1 2 3 4 5 6
| wget http://nginx.org/download/nginx-1.24.0.tar.gz tar -zxvf nginx-1.24.0.tar.gz cd nginx-1.24.0 ./configure make sudo make install
|
2.4 验证安装
三、Nginx 基本配置
3.1 配置文件结构
Nginx 的配置文件通常位于 /etc/nginx/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
| user www-data; worker_processes auto; error_log /var/log/nginx/error.log; 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; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
|
3.2 常用配置指令
- worker_processes:工作进程数,通常设置为 auto 或 CPU 核心数
- worker_connections:每个工作进程的最大连接数
- server:虚拟主机配置块
- location:URL 匹配规则
- proxy_pass:反向代理目标地址
- upstream:定义后端服务器组
四、常用功能配置
4.1 静态文件服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| server { listen 80; server_name example.com; root /var/www/html; index index.html index.htm; location / { try_files $uri $uri/ =404; } location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, immutable"; } }
|
4.2 反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| server { listen 80; server_name api.example.com; location / { proxy_pass http://localhost: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; } }
|
4.3 负载均衡
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
| upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; }
upstream backend_weighted { server backend1.example.com weight=3; server backend2.example.com weight=2; server backend3.example.com weight=1; }
upstream backend_ip_hash { ip_hash; server backend1.example.com; server backend2.example.com; }
server { listen 80; server_name example.com; location / { proxy_pass http://backend; } }
|
4.4 HTTPS/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
| server { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/ssl/certs/example.com.crt; ssl_certificate_key /etc/ssl/private/example.com.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; location / { proxy_pass http://localhost:3000; } }
server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }
|
4.5 Gzip 压缩
1 2 3 4 5 6 7 8 9 10
| http { gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml; }
|
4.6 限流配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| http { limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; limit_conn_zone $binary_remote_addr zone=addr:10m; }
server { listen 80; location / { limit_req zone=one burst=20 nodelay; limit_conn addr 10; proxy_pass http://backend; } }
|
五、常用命令
5.1 服务管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
sudo systemctl status nginx
sudo systemctl enable nginx
|
5.2 配置测试
1 2 3 4 5
| sudo nginx -t
sudo nginx -T
|
5.3 日志查看
1 2 3 4 5 6 7 8
| sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/log/nginx/*.log
|
六、常见问题处理
6.1 502 Bad Gateway
通常表示 Nginx 无法连接到后端服务器,检查:
- 后端服务是否正常运行
- proxy_pass 地址是否正确
- 防火墙是否阻止连接
- 后端服务监听地址是否正确
6.2 504 Gateway Timeout
表示后端服务响应超时,可以增加超时时间:
1 2 3 4 5 6
| location / { proxy_pass http://backend; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; }
|
6.3 权限问题
1 2 3 4 5
| sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
|
七、性能优化
7.1 工作进程优化
1 2 3 4 5 6 7 8
| worker_processes auto; worker_rlimit_nofile 65535;
events { worker_connections 4096; use epoll; multi_accept on; }
|
7.2 缓存优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server { location / { proxy_cache my_cache; proxy_cache_valid 200 60m; proxy_cache_valid 404 1m; proxy_pass http://backend; proxy_cache_bypass $http_cache_control; add_header X-Cache-Status $upstream_cache_status; } }
|
7.3 连接优化
1 2 3 4 5 6 7
| http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; keepalive_requests 100; }
|
八、安全配置
8.1 隐藏版本信息
1 2 3
| http { server_tokens off; }
|
8.2 防止点击劫持
1 2 3
| add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; add_header X-XSS-Protection "1; mode=block";
|
8.3 限制请求方法
1 2 3 4 5
| server { if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; } }
|
8.4 防止 SQL 注入
1 2 3
| location ~* \.(php|jsp|cgi|asp|aspx)$ { deny all; }
|
九、监控与日志分析
9.1 基础监控
1 2 3 4 5 6 7 8 9 10 11
| server { listen 127.0.0.1:8080; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } }
|
9.2 日志分析工具
推荐使用 GoAccess 进行实时日志分析:
1 2 3 4
| sudo apt install goaccess
sudo goaccess /var/log/nginx/access.log -c
|
Nginx 是一个功能强大、性能出色的 Web 服务器,通过合理的配置可以实现反向代理、负载均衡、缓存等功能,大大提升网站的性能和可靠性。掌握 Nginx 的配置和优化技巧,对于构建高性能的 Web 服务至关重要。