Nginx 的配置文件采用模块化结构,主要由 全局块、events 块、http 块 三部分组成,其中 http 块可包含多个 server 块(虚拟主机),每个 server 块又可包含多个 location 块(路径匹配规则)。以下是核心配置文件的详细讲解:
1. 配置文件基本结构
nginx
# 全局块:配置影响 Nginx 全局的参数
user nginx; # 运行用户,默认 nobody
worker_processes auto; # 工作进程数,通常等于 CPU 核心数
error_log /var/log/nginx/error.log warn; # 错误日志路径
pid /var/run/nginx.pid; # 进程 ID 文件位置
# events 块:配置网络连接相关参数
events {
worker_connections 1024; # 每个工作进程的最大连接数
multi_accept on; # 允许同时接受多个连接
}
# http 块:配置 HTTP 服务器的全局参数
http {
include /etc/nginx/mime.types; # MIME 类型映射文件
default_type application/octet-stream; # 默认 MIME 类型
# 日志格式定义
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; # 与 sendfile 配合,提高网络包的传输效率
keepalive_timeout 65; # 长连接超时时间
gzip on; # 启用 Gzip 压缩
# 虚拟主机配置(可包含多个 server 块)
server {
listen 80; # 监听端口
server_name example.com; # 域名或 IP
# 根路径配置
location / {
root /var/www/html; # 网站根目录
index html/index.html; # 默认首页文件
}
# 错误页面配置
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/error_pages; # 错误页面目录
}
}
# 另一个虚拟主机示例
server {
listen 80;
server_name blog.example.com;
# PHP 处理示例
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # PHP-FPM 地址
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; # 包含 FastCGI 参数配置
}
}
}
image.png
2. 核心配置块详解
全局块(Main 块)
- user:指定 Nginx 工作进程的运行用户,需确保该用户有访问网站文件的权限。
-
worker_processes:工作进程数量,通常设为
auto
(自动根据 CPU 核心数调整)或具体数值(如4
)。 -
error_log:错误日志路径和级别(
debug
、info
、warn
、error
、crit
)。
events 块
-
worker_connections:每个工作进程允许的最大并发连接数,实际最大连接数为
worker_processes × worker_connections
。 -
use:指定网络 IO 模型(
select
、poll
、epoll
等),Linux 系统推荐使用epoll
。
http 块
- include mime.types:包含 MIME 类型映射文件,用于识别文件类型。
- log_format:自定义日志格式,可记录客户端 IP、请求时间、状态码等信息。
- sendfile:启用高效文件传输模式,减少 CPU 拷贝开销。
- gzip:启用 HTTP 压缩,提高传输效率。
server 块(虚拟主机)
-
listen:监听的端口或 IP: 端口组合(如
80
、192.168.1.1:80
)。 - server_name:域名或 IP 地址,可配置多个(用空格分隔)。
- root:网站根目录,请求的文件将从该目录查找。
- index:默认首页文件列表,按顺序查找。
location 块(路径匹配)
-
语法:
location [匹配修饰符] 路径 { ... }
-
匹配修饰符:
-
=
:精确匹配(如location = /login
)。 -
~
:区分大小写的正则匹配(如location ~ \.php$
)。 -
~*
:不区分大小写的正则匹配。 -
^~
:普通字符串匹配,优先级高于正则。
-
-
常见指令:
-
root
:指定请求的根目录。 -
proxy_pass
:反向代理地址(如http://backend_server
)。 -
fastcgi_pass
:FastCGI 服务器地址(如 PHP-FPM)。 -
allow/deny
:访问控制(如allow 192.168.1.0/24; deny all;
)。
-
3. 反向代理配置示例
将 HTTP 请求转发至后端服务(如 Node.js、Tomcat):
nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000; # 后端服务地址
proxy_set_header Host $host; # 传递原始请求的 Host 头
proxy_set_header X-Real-IP $remote_addr; # 传递客户端真实 IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; # 传递请求协议(HTTP/HTTPS)
# 超时设置
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
}
4. HTTPS 配置示例
nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/fullchain.pem; # SSL 证书路径
ssl_certificate_key /etc/ssl/private/privkey.pem; # 私钥路径
# SSL 优化配置
ssl_protocols TLSv1.2 TLSv1.3; # 仅支持 TLS 1.2+
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
# HSTS 头部(可选,增强安全性)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location / {
root /var/www/html;
index index.html;
}
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
5. 性能优化配置
nginx
http {
# 连接优化
keepalive_timeout 75s;
keepalive_requests 100;
# 文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# Gzip 压缩优化
gzip on;
gzip_vary on;
gzip_types text/plain text/css application/json application/javascript;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 256;
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d; # 静态资源缓存 30 天
add_header Cache-Control "public, no-transform";
}
}
6. 配置文件加载顺序
- 主配置文件
nginx.conf
通常包含全局设置和include
指令。 - 通过
include
指令引入其他配置文件(如include /etc/nginx/conf.d/*.conf;
)。 - 虚拟主机配置可分散在多个文件中,便于管理。
7. 测试与重载配置
修改配置后,需先测试语法,再重载服务:
bash
nginx -t # 测试配置语法
nginx -s reload # 重载配置(无需重启服务)
通过合理配置 Nginx,可实现高性能负载均衡、静态资源优化、安全防护等功能。建议根据实际需求调整参数,并定期检查配置文件的安全性。