Nginx高性能服务器配置完全指南:从负载均衡到直播服务器的实战教程
Nginx是一款高性能的HTTP和反向代理服务器,以其高并发、低资源消耗的特点,成为全球最受欢迎的Web服务器之一。本文将从基础配置到高级应用,全面介绍Nginx的实战技巧,帮助读者构建高性能、高可用的Web服务架构。
一、Nginx基础安装与配置
1.1 安装Nginx
CentOS 7使用YUM安装:
1 2 3 4 5 6 7 8 9 10 11 12
| sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
sudo yum install -y nginx
sudo systemctl start nginx sudo systemctl enable nginx
sudo systemctl status nginx
|
源码编译安装(推荐用于生产环境):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| wget http://nginx.org/download/nginx-1.24.0.tar.gz tar -zxvf nginx-1.24.0.tar.gz cd nginx-1.24.0
yum install -y pcre pcre-devel zlib zlib-devel openssl openssl-devel gcc gcc-c++ make
./configure \ --prefix=/usr/local/nginx \ --with-http_stub_status_module \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_realip_module \ --with-http_gzip_static_module
make && make install
/usr/local/nginx/sbin/nginx
|
1.2 配置文件结构
Nginx配置文件位于 /usr/local/nginx/conf/nginx.conf,主要包含以下部分:
1 2 3 4 5 6 7
| nginx.conf ├── 全局块 # 影响Nginx全局运行的指令 ├── events块 # 配置Nginx与用户的网络连接 ├── http块 # HTTP服务器配置 │ ├── server块 # 虚拟主机配置 │ │ ├── location块 # URL路由配置 │ └── upstream块 # 负载均衡配置
|
1.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 30 31 32 33 34 35 36 37 38
| user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;
events { worker_connections 4096; 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;
gzip on; gzip_types text/plain text/css application/json application/javascript;
include /etc/nginx/conf.d/*.conf; }
|
二、虚拟主机配置
2.1 基于域名的虚拟主机
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| server { listen 80; server_name example.com www.example.com;
root /var/www/example; index index.html index.htm;
location / { try_files $uri $uri/ =404; }
error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /var/www/error; } }
|
2.2 基于端口的虚拟主机
1 2 3 4 5 6 7
| server { listen 8080; server_name localhost;
root /var/www/admin; index index.html; }
|
2.3 基于IP的虚拟主机
1 2 3 4 5 6 7 8 9 10 11 12 13
| server { listen 192.168.1.100:80; server_name localhost;
root /var/www/site1; }
server { listen 192.168.1.101:80; server_name localhost;
root /var/www/site2; }
|
2.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 example.com;
root /var/www/example;
location /static/ { alias /var/www/static/; expires 30d; }
location ~* \.(gif|jpg|jpeg|png|css|js)$ { expires 1d; }
location /old-path { rewrite ^/old-path(.*)$ /new-path$1 permanent; }
location / { try_files $uri $uri/ /index.php?$query_string; } }
|
三、负载均衡配置
3.1 基本负载均衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| upstream backend { server 192.168.1.10:8080 weight=5; server 192.168.1.11:8080 weight=3; server 192.168.1.12:8080 backup; }
server { listen 80; server_name app.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; proxy_set_header X-Forwarded-Proto $scheme; } }
|
3.2 负载均衡算法
| 算法 |
指令 |
说明 |
| 轮询 |
默认 |
请求按顺序分配到各服务器 |
| 权重 |
weight |
根据权重分配请求 |
| IP哈希 |
ip_hash |
按客户端IP固定分配 |
| 最少连接 |
least_conn |
分配到当前连接最少的服务器 |
| 一致性哈希 |
hash |
按指定key的hash值分配 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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 { hash $request_uri consistent; server 192.168.1.10:8080; server 192.168.1.11:8080; }
|
3.3 健康检查
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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 down; }
server { location / { proxy_pass http://backend; proxy_next_upstream error timeout http_500 http_502 http_503 http_504; proxy_next_upstream_tries 2; } }
|
四、HTTPS配置
4.1 证书申请与配置
使用Let’s Encrypt免费证书:
1 2 3 4 5 6 7 8
| yum install -y certbot python2-certbot-nginx
certbot --nginx -d example.com -d www.example.com
certbot renew --dry-run
|
手动配置证书:
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
| server { listen 443 ssl http2; server_name 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 on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d; ssl_session_tickets off;
add_header Strict-Transport-Security "max-age=63072000" always;
root /var/www/example; index index.html; }
server { listen 80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; }
|
4.2 SSL性能优化
1 2 3 4 5 6 7 8 9 10
| 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;
ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d;
|
五、反向代理与缓存
5.1 反向代理配置
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_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s;
proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; } }
|
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
| server { location /static/ { alias /var/www/static/;
expires 1y; add_header Cache-Control "public, immutable";
gzip on; gzip_types text/css application/javascript;
valid_referers none blocked server_names *.example.com; if ($invalid_referer) { return 403; } }
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ { expires 1M; access_log off; add_header Cache-Control "public"; } }
|
5.3 代理缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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_cache my_cache; proxy_pass http://backend;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502;
add_header X-Cache-Status $upstream_cache_status; } }
|
六、RTMP直播服务器搭建
6.1 编译安装RTMP模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| wget http://nginx.org/download/nginx-1.24.0.tar.gz wget https://github.com/arut/nginx-rtmp-module/archive/master.zip
tar -zxvf nginx-1.24.0.tar.gz unzip master.zip
cd nginx-1.24.0 ./configure \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --add-module=../nginx-rtmp-module-master
make && make install
|
6.2 RTMP配置
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 81 82
| worker_processes auto; events { worker_connections 1024; }
rtmp { server { listen 1935; chunk_size 4096;
application live { live on;
record all; record_path /var/recordings; record_unique on; record_suffix .flv;
on_publish http://localhost:8080/auth; on_publish_done http://localhost:8080/done;
hls on; hls_path /var/hls; hls_fragment 3; hls_playlist_length 60;
exec ffmpeg -i rtmp://localhost/live/$name -c:v libx264 -c:a aac -b:v 256k -b:a 32k -vf "scale=480:trunc(ow/a/2)*2" -tune zerolatency -preset superfast -f flv rtmp://localhost/live360p/$name -c:v libx264 -c:a aac -b:v 512k -b:a 64k -vf "scale=720:trunc(ow/a/2)*2" -tune zerolatency -preset superfast -f flv rtmp://localhost/live720p/$name; }
application playback { live on; play /var/recordings; } } }
http { include mime.types; default_type application/octet-stream;
server { listen 80; server_name localhost;
location /hls { types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; } root /var; add_header Cache-Control no-cache; add_header Access-Control-Allow-Origin *; }
location /stat { rtmp_stat all; rtmp_stat_stylesheet stat.xsl; }
location /stat.xsl { root /usr/local/nginx/html; }
location / { root /var/www; index index.html; } } }
|
6.3 推流与播放
推流URL:
1
| rtmp://your-server/live/stream_key
|
播放URL:
1 2 3
| RTMP: rtmp://your-server/live/stream_key HLS: http://your-server/hls/stream_key.m3u8 FLV: http://your-server/flv?port=1935&app=live&stream=stream_key
|
七、性能优化
7.1 系统优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| cat >> /etc/security/limits.conf << EOF * soft nofile 65535 * hard nofile 65535 EOF
cat >> /etc/sysctl.conf << EOF net.core.somaxconn = 65535 net.ipv4.tcp_max_tw_buckets = 6000 net.ipv4.tcp_sack = 1 net.ipv4.tcp_window_scaling = 1 net.ipv4.tcp_rmem = 4096 87380 4194304 net.ipv4.tcp_wmem = 4096 16384 4194304 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 EOF
sysctl -p
|
7.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 32 33 34 35
| worker_processes auto; worker_rlimit_nofile 65535;
events { worker_connections 65535; use epoll; multi_accept on; accept_mutex off; }
http { open_file_cache max=65535 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2;
sendfile on; tcp_nopush on; tcp_nodelay on;
keepalive_timeout 30; keepalive_requests 1000; reset_timedout_connection on; client_body_timeout 10; send_timeout 2;
gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml application/json application/javascript; }
|
八、安全加固
8.1 隐藏版本信息
1 2 3
| http { server_tokens off; }
|
8.2 限制请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 10;
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; limit_req zone=one burst=5 nodelay;
server { location /api/ { limit_req zone=one; limit_conn addr 5; } }
|
8.3 访问控制
1 2 3 4 5 6 7 8 9 10 11
| location /admin/ { allow 192.168.1.0/24; deny all; }
location /secure/ { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; }
|
8.4 防攻击配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| if ($query_string ~* "union.*select.*\(") { return 403; }
if ($http_user_agent ~* (wget|curl|python|nikto|sqlmap)) { return 403; }
location ~* \.\./ { return 403; }
|
九、日志管理与分析
9.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
| #!/bin/bash
LOG_PATH="/var/log/nginx" BACKUP_PATH="/var/log/nginx/backup" DATE=$(date -d "yesterday" +%Y%m%d) PID_FILE="/var/run/nginx.pid"
mkdir -p ${BACKUP_PATH}
cd ${LOG_PATH} for log in *.log; do if [ -f "$log" ]; then mv "$log" "${BACKUP_PATH}/${log}.${DATE}" gzip "${BACKUP_PATH}/${log}.${DATE}" fi done
kill -USR1 $(cat ${PID_FILE})
find ${BACKUP_PATH} -name "*.gz" -mtime +30 -delete
echo "$(date): Nginx log rotated" >> /var/log/nginx/rotate.log
|
9.2 日志分析命令
1 2 3 4 5 6 7 8 9 10 11 12
| awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
awk '{print $NF " " $7}' /var/log/nginx/access.log | sort -rn | head -20
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
awk '{print $4}' /var/log/nginx/access.log | cut -d: -f1 | sort | uniq -c awk '{print $1}' /var/log/nginx/access.log | sort | uniq | wc -l
|
十、总结
Nginx凭借其优秀的性能和灵活的配置,成为现代Web架构中不可或缺的组件。本文涵盖了:
- 基础安装:YUM安装和源码编译两种方式
- 虚拟主机:域名、端口、IP三种虚拟主机配置
- 负载均衡:多种负载均衡算法和配置技巧
- HTTPS部署:SSL证书配置和性能优化
- 反向代理:代理配置和缓存策略
- RTMP直播:直播服务器的搭建和配置
- 性能优化:系统和Nginx层面的优化
- 安全加固:访问控制、限流、防攻击
- 日志管理:日志切割和分析
在实际生产环境中,建议:
- 定期更新Nginx版本,修复安全漏洞
- 建立完善的监控告警体系
- 做好配置文件版本控制
- 定期进行性能测试和容量评估
- 制定故障应急预案
通过合理的架构设计和持续的优化调整,可以构建高性能、高可用的Web服务体系。