nginx核心配置文件结构
Nginx 配置文件的组织方式决定了服务器的行为,下面解析核心配置段的作用与层级关系。
配置文件层级
nginx
# main 段(全局上下文)
worker_processes auto;
events {
# events 段
worker_connections 1024;
}
http {
# http 段
include mime.types;
server {
# server 段
listen 80;
location / {
# location 段
root /var/www/html;
}
}
}
配置段层级关系
| 配置段 | 上级 | 下级 | 作用 |
|---|---|---|---|
| main | 无 | events, http, mail, stream | 全局上下文 |
| events | main | 无 | 连接处理 |
| http | main | server, upstream, map, geo | HTTP 服务 |
| server | http | location, if | 虚拟主机 |
| location | server | if, limit_except | 路径匹配 |
| upstream | http | server | 负载均衡 |
| stream | main | server | 四层代理 |
| main | server | 邮件代理 |
main 段可配置项
nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events 段
nginx
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http 段
nginx
http {
# 基础
include mime.types;
default_type application/octet-stream;
# 日志
log_format main '...';
access_log /var/log/nginx/access.log;
# 传输优化
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
# 压缩
gzip on;
# 虚拟主机
include /etc/nginx/conf.d/*.conf;
}
server 段
nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
}
location 段
nginx
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}
注意事项
- 配置段可嵌套,子段继承父段配置
- 同一层级可存在多个 server 或 location
- mail 和 stream 段与 http 段平级,不可在 http 内使用
- 生产环境建议将 server 配置拆分到 conf.d 目录
模块化配置
nginx
# nginx.conf
http {
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
拆分后每个 .conf 文件只包含一个 server 块。
要点总结
- 配置文件采用 main → events/http → server → location 层级
- main 段定义全局参数,events 段处理连接,http 段处理 HTTP 请求
- server 段定义虚拟主机,location 段定义路径匹配规则
- stream 和 mail 段与 http 段平级,分别用于四层代理和邮件代理
- 生产环境建议将 server 配置拆分到 conf.d 或 sites-enabled 目录
📝 发现内容有误?点击此处直接编辑