以下为 Nginx 配置文件详解(以标准 /etc/nginx/nginx.conf 为例):
一、配置文件结构
# 全局配置区
user nginx; # 运行用户
worker_processes auto; # 工作进程数(通常设为 CPU 核心数)
error_log /var/log/nginx/error.log; # 错误日志路径
events {
# 事件模型配置
worker_connections 1024; # 单个进程最大并发连接数
use epoll; # Linux 高性能网络模型(可选)
}
http {
# HTTP 核心配置区
include /etc/nginx/mime.types; # MIME 类型映射文件
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; # 减少网络报文段数量
keepalive_timeout 65; # 长连接超时时间
# 虚拟主机配置容器
server {
listen 80; # 监听端口
server_name example.com; # 域名
location / {
# URL 路径匹配规则
root /var/www/html; # 站点根目录
index index.html; # 默认索引文件
}
}
# 可包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}二、核心模块详解
1. events 块
worker_connections:单个工作进程的最大并发连接数(总并发 =worker_processes × worker_connections)。use:指定事件模型,如epoll(Linux 高效模型)、kqueue(BSD)。
2. http 块
日志配置:
log_format custom '$request_time $upstream_response_time'; # 自定义日志格式 access_log logs/access.log custom; # 应用自定义格式性能参数:
gzip on; # 开启 Gzip 压缩 gzip_types text/css application/json; # 指定压缩类型 client_max_body_size 100M; # 最大上传文件大小
3. server 块(虚拟主机)
基础配置:
server { listen 443 ssl http2; # HTTPS + HTTP/2 server_name api.example.com; # 支持通配符 *.example.com ssl_certificate /etc/ssl/cert.pem; # SSL 证书 ssl_certificate_key /etc/ssl/key.pem; # 私钥 }
4. location 块(路径匹配)
匹配规则优先级:
location = /path# 精确匹配(最高)location ^~ /path# 前缀匹配(不检查正则)location ~ \.php$# 正则匹配(区分大小写)location /# 通用匹配(最低)
常见场景:
# 反向代理 location /api/ { proxy_pass http://backend_server; # 转发到后端 proxy_set_header Host $host; # 传递原始 Host } # 静态文件 location /static/ { alias /data/static/; # 目录映射(注意与 root 的区别) expires 30d; # 缓存过期时间 } # 动态请求 location ~ \.php$ { fastcgi_pass unix:/var/run/php-fpm.sock; # PHP-FPM include fastcgi_params; }
三、高级配置示例
负载均衡
upstream backend {
server 192.168.1.100 weight=3; # 权重
server 192.168.1.101;
server 192.168.1.102 backup; # 备用节点
least_conn; # 最少连接算法
}
server {
location / {
proxy_pass http://backend;
}
}安全防护
# 禁止敏感文件访问
location ~* \.(sql|bak|conf)$ {
deny all;
}
# 防爬虫
if ($http_user_agent ~* (bot|crawler)) {
return 403;
}HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri; # 301 永久重定向
}四、调试与验证
检查配置语法:
sudo nginx -t # 测试配置是否正确输出示例:
nginx: configuration file /etc/nginx/nginx.conf test is successful重载配置:
sudo nginx -s reload # 不重启服务加载新配置查看运行配置:
nginx -T # 打印实际生效的配置(含 include 文件)
五、配置文件路径
- 主配置:
/etc/nginx/nginx.conf 模块化配置:
conf.d/:自定义 server 配置sites-available/&sites-enabled/(Debian 系):虚拟主机配置modules-enabled/:动态模块配置
附:关键变量表
| 变量 | 说明 |
|---|---|
$remote_addr | 客户端 IP 地址 |
$request | 请求行(如 GET / HTTP/1.1) |
$status | HTTP 响应状态码 |
$http_user_agent | 客户端浏览器标识 |
$scheme | 协议(http / https) |
提示:
- 使用
include拆分配置,避免单个文件过大。 - 修改配置后务必执行
nginx -t验证语法。
评论 (0)