Nginx高性能服务器配置完全指南:从负载均衡到直播服务器的实战教程

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
# 添加Nginx官方源
sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

# 安装Nginx
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

# 启动Nginx
/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; # 自动根据CPU核心数设置
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

# events块
events {
worker_connections 4096; # 每个worker的连接数
use epoll; # 使用epoll模型(Linux)
multi_accept on; # 允许同时接受多个连接
}

# http块
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压缩
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;
}

# URL重写
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块定义后端服务器组
upstream backend {
server 192.168.1.10:8080 weight=5; # 权重5
server 192.168.1.11:8080 weight=3; # 权重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
# IP哈希(会话保持)
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
# 安装Certbot
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优化配置
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;

# HSTS(强制HTTPS)
add_header Strict-Transport-Security "max-age=63072000" always;

root /var/www/example;
index index.html;
}

# HTTP重定向到HTTPS
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
# 开启OCSP Stapling
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会话缓存
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
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
# 下载Nginx和RTMP模块
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配置
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支持
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配置
http {
include mime.types;
default_type application/octet-stream;

server {
listen 80;
server_name localhost;

# HLS播放
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 *;
}

# RTMP统计
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压缩
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
# IP黑白名单
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
# 防止SQL注入
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})

# 删除30天前的日志
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
# 统计IP访问次数
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

# 统计PV和UV
awk '{print $4}' /var/log/nginx/access.log | cut -d: -f1 | sort | uniq -c # PV
awk '{print $1}' /var/log/nginx/access.log | sort | uniq | wc -l # UV

十、总结

Nginx凭借其优秀的性能和灵活的配置,成为现代Web架构中不可或缺的组件。本文涵盖了:

  1. 基础安装:YUM安装和源码编译两种方式
  2. 虚拟主机:域名、端口、IP三种虚拟主机配置
  3. 负载均衡:多种负载均衡算法和配置技巧
  4. HTTPS部署:SSL证书配置和性能优化
  5. 反向代理:代理配置和缓存策略
  6. RTMP直播:直播服务器的搭建和配置
  7. 性能优化:系统和Nginx层面的优化
  8. 安全加固:访问控制、限流、防攻击
  9. 日志管理:日志切割和分析

在实际生产环境中,建议:

  • 定期更新Nginx版本,修复安全漏洞
  • 建立完善的监控告警体系
  • 做好配置文件版本控制
  • 定期进行性能测试和容量评估
  • 制定故障应急预案

通过合理的架构设计和持续的优化调整,可以构建高性能、高可用的Web服务体系。