Nginx 配置文件详解
Nginx 的配置文件是 Nginx 服务器的核心,掌握配置文件的语法和指令是熟练使用 Nginx 的关键。本章将深入讲解 Nginx 配置文件的结构、常用指令和配置技巧。
配置文件结构
Nginx 配置文件默认位于 /etc/nginx/nginx.conf,采用层级结构组织:
# 全局块:影响 Nginx 全局的配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# events 块:连接处理配置
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
# http 块: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_types text/plain text/css application/json application/javascript;
# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
# server 块:虚拟主机配置
server {
listen 80;
server_name example.com www.example.com;
# location 块:URL 路由配置
location / {
root /var/www/html;
index index.html index.htm;
}
location /api/ {
proxy_pass http://backend_server;
}
}
}
配置块层级关系
nginx.conf
├── 全局块
├── events 块
└── http 块
├── 全局 HTTP 配置
├── server 块(虚拟主机)
│ ├── server 全局配置
│ └── location 块(路由规则)
│ └── 具体 location 配置
└── upstream 块(后端服务器组)
全局块配置
全局块的指令影响 Nginx 服务器的整体运行。
基本指令
# 设置运行 Nginx worker 进程的用户
user nginx;
# 设置 worker 进程数,通常设置为 CPU 核心数
worker_processes auto; # 或具体数字如 4
# 错误日志位置和级别
error_log /var/log/nginx/error.log warn;
# 级别:debug | info | notice | warn | error | crit | alert | emerg
# PID 文件位置
pid /var/run/nginx.pid;
# 设置工作进程打开文件数限制
worker_rlimit_nofile 65535;
性能优化指令
# 工作进程绑定到指定 CPU 核心,减少 CPU 切换开销
worker_cpu_affinity auto;
# 或手动指定:worker_cpu_affinity 0001 0010 0100 1000;
# 设置工作进程的优先级
worker_priority -5; # 范围:-20 到 20,值越小优先级越高
Events 块配置
Events 块配置影响 Nginx 与客户端的连接处理方式。
events {
# 每个 worker 进程的最大连接数
worker_connections 1024;
# 连接处理模型
use epoll; # Linux 推荐,其他系统:kqueue(FreeBSD)、/dev/poll(Solaris)
# 允许一个 worker 同时接受多个新连接
multi_accept on;
# 启用网络连接序列化,防止惊群效应
accept_mutex on;
accept_mutex_delay 500ms;
}
最大并发连接数计算
最大并发连接数 = worker_processes × worker_connections
例如:
- worker_processes = 4
- worker_connections = 1024
- 最大并发连接数 = 4 × 1024 = 4096
HTTP 块配置
HTTP 块是 Nginx 最常用的配置块,包含 HTTP 服务的所有配置。
基本配置
http {
# 包含 MIME 类型文件
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 字符集
charset utf-8;
# 服务器名称哈希表大小
server_names_hash_bucket_size 64;
server_names_hash_max_size 512;
}
日志配置
http {
# 定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$ssl_protocol $ssl_cipher';
# 访问日志
access_log /var/log/nginx/access.log main;
# 关闭特定 location 的访问日志
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
access_log off;
expires 30d;
}
}
性能优化
http {
# 启用 sendfile,提高静态文件传输效率
sendfile on;
# 配合 sendfile 使用,提高大文件传输效率
tcp_nopush on;
# 立即发送小数据包,降低延迟
tcp_nodelay on;
# 长连接超时时间
keepalive_timeout 65;
# 长连接最大请求数
keepalive_requests 1000;
# 客户端请求头缓冲区大小
client_header_buffer_size 4k;
large_client_header_buffers 4 8k;
# 客户端请求体大小限制
client_max_body_size 50m;
# 客户端请求体缓冲区
client_body_buffer_size 128k;
}
Gzip 压缩配置
http {
# 启用 Gzip 压缩
gzip on;
# 压缩级别(1-9,值越大压缩率越高,CPU 消耗越大)
gzip_comp_level 6;
# 最小压缩文件大小
gzip_min_length 1k;
# 压缩缓冲区
gzip_buffers 16 8k;
# 压缩版本
gzip_http_version 1.1;
# 需要压缩的 MIME 类型
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml
application/xml+rss text/javascript;
# 为代理请求启用压缩
gzip_proxied any;
# 添加 Vary: Accept-Encoding 响应头
gzip_vary on;
# 禁用对 IE6 的压缩
gzip_disable "MSIE [1-6]\.";
}
Server 块配置
Server 块定义虚拟主机,处理特定的域名或端口请求。
基本 Server 配置
server {
# 监听端口
listen 80;
listen [::]:80; # IPv6
# 服务器名称(域名)
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 main;
error_log /var/log/nginx/example.com.error.log warn;
}
多域名配置
# 方式一:多个 server 块
server {
listen 80;
server_name site1.com www.site1.com;
root /var/www/site1;
}
server {
listen 80;
server_name site2.com www.site2.com;
root /var/www/site2;
}
# 方式二:通配符和正则
server {
listen 80;
server_name *.example.com; # 通配符
root /var/www/subdomains;
}
server {
listen 80;
server_name ~^(www\.)?(?<domain>.+)$; # 正则匹配
root /var/www/$domain;
}
HTTPS 配置
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_session_cache shared:SSL:50m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# SSL 协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/ssl/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# 安全响应头
add_header Strict-Transport-Security "max-age=63072000" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
root /var/www/example.com;
index index.html;
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
Location 块配置
Location 块定义 URL 路由规则,是 Nginx 配置中最灵活的部分。
Location 匹配规则
server {
listen 80;
server_name example.com;
# 精确匹配(优先级最高)
location = /exact {
return 200 "Exact match\n";
}
# 前缀匹配(^~ 表示如果匹配成功,不再检查正则)
location ^~ /static/ {
root /var/www/static;
expires 30d;
}
# 正则匹配(区分大小写)
location ~ \.(gif|jpg|png)$ {
root /var/www/images;
expires 30d;
}
# 正则匹配(不区分大小写)
location ~* \.(css|js)$ {
root /var/www/assets;
expires 1y;
add_header Cache-Control "public, immutable";
}
# 通用前缀匹配(优先级最低)
location / {
root /var/www/html;
index index.html;
}
}
Location 匹配优先级
1. = 精确匹配
2. ^~ 前缀匹配(匹配后停止搜索)
3. ~ 或 ~* 正则匹配(按配置文件中的顺序)
4. 无修饰符 普通前缀匹配
常用 Location 配置示例
server {
listen 80;
server_name api.example.com;
# API 代理
location /api/ {
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;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时设置
proxy_connect_timeout 5s;
proxy_send_timeout 10s;
proxy_read_timeout 10s;
}
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www/static;
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 禁止访问敏感文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
location ~* \.(git|svn|hg|env|log)$ {
deny all;
}
# PHP 处理
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 前端路由支持(SPA)
location / {
try_files $uri $uri/ /index.html;
}
# 负载均衡示例
location /app/ {
proxy_pass http://app_servers;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Upstream 配置
Upstream 定义后端服务器组,用于负载均衡。
基本 Upstream 配置
# 定义后端服务器组
upstream backend_servers {
# 负载均衡方法(默认轮询)
# least_conn; # 最少连接
# ip_hash; # IP 哈希(会话保持)
# hash $request_uri consistent; # URI 哈希
# 后端服务器
server 192.168.1.10:8080 weight=5;
server 192.168.1.11:8080 weight=5;
server 192.168.1.12:8080 backup; # 备用服务器
server 192.168.1.13:8080 down; # 暂时下线
# 健康检查(需要 nginx_upstream_check_module)
# 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 {
listen 80;
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
负载均衡算法
# 1. 轮询(默认)
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 2. 加权轮询
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=7;
}
# 3. IP 哈希(会话保持)
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 4. 最少连接
upstream backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 5. 加权最少连接
upstream backend {
least_conn;
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=7;
}
# 6. URI 哈希
upstream backend {
hash $request_uri consistent;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
完整配置示例
静态网站配置
server {
listen 80;
server_name static.example.com;
root /var/www/static;
index index.html;
# 字符集
charset utf-8;
# 缓存静态资源
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
expires 6M;
add_header Cache-Control "public, immutable";
access_log off;
}
# Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json
application/javascript text/xml;
# 安全响应头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
反向代理配置
upstream app_servers {
least_conn;
server 127.0.0.1:3000 weight=5;
server 127.0.0.1:3001 weight=5;
keepalive 32;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://app_servers;
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 Connection "";
# 超时设置
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲区设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
# 错误处理
proxy_intercept_errors on;
error_page 500 502 503 504 /50x.html;
}
location = /50x.html {
root /var/www/errors;
}
# 静态文件直接由 Nginx 处理
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www/app/static;
expires 30d;
access_log off;
}
}
配置测试和重载
# 测试配置文件语法
nginx -t
# 测试指定配置文件
nginx -t -c /etc/nginx/nginx.conf
# 重载配置(不中断服务)
nginx -s reload
# 快速停止
nginx -s stop
# 优雅停止
nginx -s quit
# 重新打开日志文件
nginx -s reopen
小结
- 配置文件结构:全局块 → events 块 → http 块 → server 块 → location 块
- 全局配置:worker 进程、错误日志、PID 文件
- Events 配置:连接处理、并发模型
- HTTP 配置:日志、压缩、性能优化
- Server 配置:虚拟主机、域名、端口
- Location 配置:URL 路由、匹配规则
- Upstream 配置:负载均衡、后端服务器组
练习
- 配置一个支持 HTTPS 的虚拟主机
- 设置 Gzip 压缩,优化静态资源传输
- 配置负载均衡,实现后端服务器的故障转移
- 配置 Location 规则,实现不同 URL 的路由分发