Nginx配置

Nginx 详细配置手册

目录

  1. Nginx 安装和基本配置
  2. 核心配置详解
  3. 虚拟主机配置
  4. 负载均衡配置
  5. 反向代理配置
  6. HTTPS 和 SSL 配置
  7. 缓存和性能优化
  8. 安全配置
  9. 日志配置
  10. 常见问题排查

Nginx 安装和基本配置

1. 安装 Nginx

CentOS/RHEL:

1
2
3
4
5
6
7
8
9
# 添加 EPEL 仓库
yum install -y epel-release

# 安装 Nginx
yum install -y nginx

# 启动并设置开机自启
systemctl enable nginx
systemctl start nginx

Ubuntu/Debian:

1
2
3
4
5
6
7
8
9
# 更新包列表
apt update

# 安装 Nginx
apt install -y nginx

# 启动并设置开机自启
systemctl enable nginx
systemctl start nginx

编译安装(最新版本):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 安装依赖
yum groupinstall -y "Development Tools"
yum install -y pcre-devel zlib-devel openssl-devel

# 下载并编译
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 --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_realip_module

make && make install

2. 目录结构

1
2
3
4
5
6
7
8
9
10
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置文件目录
├── sites-available/ # 可用的站点配置
├── sites-enabled/ # 已启用的站点配置
├── modules/ # 模块目录
└── ssl/ # SSL证书目录

/var/log/nginx/ # 日志目录
/usr/share/nginx/html/ # 默认网站根目录

3. 基本操作命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 检查配置文件语法
nginx -t

# 重新加载配置(不中断服务)
nginx -s reload

# 停止服务
nginx -s stop

# 优雅停止(处理完当前请求)
nginx -s quit

# 查看版本和编译参数
nginx -V

# 系统服务管理
systemctl status nginx
systemctl restart nginx
systemctl reload nginx

核心配置详解

1. 主配置文件结构 (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 运行用户和组
user nginx nginx;

# worker进程数,通常等于CPU核心数
worker_processes auto;

# 错误日志路径和级别
error_log /var/log/nginx/error.log warn;

# PID文件位置
pid /var/run/nginx.pid;

# 事件模块配置
events {
# 每个worker最大连接数
worker_connections 1024;

# 使用epoll(Linux)
use epoll;

# 允许同时接受多个连接
multi_accept on;
}

# HTTP模块配置
http {
# MIME类型
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;

# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

虚拟主机配置

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 example.com www.example.com;

# 网站根目录
root /var/www/example.com;
index index.html index.htm index.php;

# 字符集
charset utf-8;

# 访问日志
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;

location / {
try_files $uri $uri/ =404;
}

# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}

2. PHP 应用配置(WordPress等)

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 phpapp.com;
root /var/www/phpapp;
index index.php index.html index.htm;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;

# 安全设置
fastcgi_param HTTP_PROXY "";
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
}

# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}

3. Node.js 应用反向代理

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 nodeapp.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;

# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}

4. Python Django/Flask 应用

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 80;
server_name pythonapp.com;

location /static/ {
alias /var/www/pythonapp/static/;
expires 30d;
add_header Cache-Control "public";
}

location /media/ {
alias /var/www/pythonapp/media/;
expires 30d;
add_header Cache-Control "public";
}

location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $http_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;

# WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}

负载均衡配置

1. 基本负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
upstream backend_servers {
# 默认轮询
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

server {
listen 80;
server_name loadbalance.com;

location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

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
upstream backend_servers {
# 权重分配
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 weight=1;

# 最少连接数
least_conn;

# 健康检查
server 192.168.1.13:8080 backup;
}

upstream app_servers {
# IP哈希(会话保持)
ip_hash;
server 192.168.1.20:8080;
server 192.168.1.21:8080;
server 192.168.1.22:8080;
}

upstream geo_servers {
# 基于客户端IP的哈希
hash $remote_addr consistent;
server 192.168.1.30:8080;
server 192.168.1.31:8080;
}

3. 健康检查配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;

# 健康检查
check interval=3000 rise=2 fall=5 timeout=1000 type=http;
check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}

server {
location /nginx_status {
check_status;
access_log off;
allow 192.168.1.0/24;
deny all;
}
}

反向代理配置

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
server {
listen 80;
server_name proxy.com;

location /app/ {
# 重写URL
rewrite ^/app/(.*) /$1 break;

proxy_pass http://backend_server;
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_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;

# 超时设置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
}

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
location /api/ {
proxy_pass http://api_backend;

# 安全头
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# 连接设置
proxy_redirect off;
proxy_http_version 1.1;

# 缓冲区优化
proxy_buffers 16 32k;
proxy_buffer_size 64k;
proxy_busy_buffers_size 64k;

# 超时设置
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 错误处理
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
}

HTTPS 和 SSL 配置

1. 基本 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
server {
listen 443 ssl http2;
server_name example.com;

# SSL证书路径
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-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;

# 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# 安全头
add_header Strict-Transport-Security "max-age=63072000" always;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;

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

2. HTTP 重定向到 HTTPS

1
2
3
4
5
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}

3. 免费 SSL (Let’s Encrypt)

1
2
3
4
5
6
7
8
9
10
11
# 安装 certbot
yum install -y certbot python3-certbot-nginx

# 获取证书
certbot --nginx -d example.com -d www.example.com

# 自动续期测试
certbot renew --dry-run

# 设置自动续期定时任务
echo "0 0,12 * * * root python3 -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null

缓存和性能优化

1. 代理缓存配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 在http块中定义缓存路径
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_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 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;

add_header X-Cache-Status $upstream_cache_status;

proxy_pass http://backend;
}
}

2. 静态文件缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server {
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Vary Accept-Encoding;

# 文件不存在时不代理到后端
try_files $uri =404;
}

location ~* \.(html|htm)$ {
expires 1h;
add_header Cache-Control "public";
}
}

3. Gzip 压缩优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
gzip on;
gzip_vary on;
gzip_min_length 1024;
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/atom+xml
image/svg+xml;

安全配置

1. 基本安全设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {
# 隐藏Nginx版本号
server_tokens off;

# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# 文件上传大小限制
client_max_body_size 10m;

# 防止点击劫持
add_header X-Frame-Options DENY;
}

2. 访问控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
location /admin/ {
# IP白名单
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;

# 基础认证
auth_basic "Administrator's Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}

location ~ /\.ht {
deny all;
}

# 限制请求方法
location /api/ {
limit_except GET POST {
deny all;
}
}

3. 速率限制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 在http块中定义限制区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/m;

server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://api_backend;
}

location /login {
limit_req zone=login burst=5;
proxy_pass http://auth_backend;
}
}

日志配置

1. 自定义日志格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';

log_format json_analytics escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status": "$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"request_time":$request_time,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"http_x_forwarded_for":"$http_x_forwarded_for"'
'}';

access_log /var/log/nginx/access.log main;
}

2. 日志分割和管理

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
# logrotate_nginx.sh

# 重命名日志文件
mv /var/log/nginx/access.log /var/log/nginx/access_$(date +%Y%m%d).log
mv /var/log/nginx/error.log /var/log/nginx/error_$(date +%Y%m%d).log

# 重新打开日志文件
kill -USR1 $(cat /var/run/nginx.pid)

# 删除30天前的日志
find /var/log/nginx/ -name "*.log" -mtime +30 -delete

常见问题排查

1. 配置检查

1
2
3
4
5
6
7
8
# 检查配置文件语法
nginx -t

# 检查特定配置文件
nginx -t -c /etc/nginx/nginx.conf

# 查看加载的配置
nginx -T

2. 日志分析

1
2
3
4
5
6
7
8
9
10
11
# 实时查看访问日志
tail -f /var/log/nginx/access.log

# 查看错误日志
tail -f /var/log/nginx/error.log

# 统计状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn

# 查找最频繁的IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20

3. 性能监控

1
2
3
4
5
6
7
8
9
10
11
12
# 启用状态页面
server {
listen 8080;
server_name 127.0.0.1;

location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}

4. 常见错误解决

502 Bad Gateway

1
2
3
4
5
6
7
8
9
10
11
12
location / {
proxy_pass http://backend;

# 增加超时时间
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 调整缓冲区
proxy_buffers 8 16k;
proxy_buffer_size 32k;
}

413 Request Entity Too Large

1
2
3
4
5
6
7
server {
client_max_body_size 100M;

location /upload {
client_max_body_size 500M;
}
}

这份 Nginx 配置手册涵盖了从基础到高级的各种配置场景,可以根据实际需求选择相应的配置片段进行使用。记得在修改配置后使用 nginx -t 测试语法,然后重新加载配置。