配置文件结构
约 619 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 快速入门(在新窗口打开) › 配置文件结构
配置文件路径
| 安装方式 | 主配置文件路径 |
|---|---|
| macOS Homebrew | /opt/homebrew/etc/nginx/nginx.conf |
| Ubuntu apt | /etc/nginx/nginx.conf |
| CentOS yum | /etc/nginx/nginx.conf |
| Docker | /etc/nginx/nginx.conf |
完整配置示例
# /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;
multi_accept on;
}
# http 块 —— 配置 HTTP 服务相关
http {
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;
gzip on;
# 引入其他配置文件
include /etc/nginx/conf.d/*.conf;
# server 块 —— 虚拟主机
server {
listen 80;
server_name example.com;
# location 块 —— URI 匹配及处理
location / {
root /var/www/html;
index index.html;
}
location /api/ {
proxy_pass http://backend:3000;
}
error_page 404 /404.html;
}
}配置层级
| 上下文 | 作用 | 可嵌套 |
|---|---|---|
main(全局) | 进程、日志、用户等全局设置 | 无 |
events | 网络连接处理 | 仅 main 下 |
http | HTTP 协议相关 | main 下 |
server | 虚拟主机(域名 + 端口) | http 下 |
location | URI 路径匹配和处理 | server 下 |
include 机制
http {
# 引入 conf.d 下所有 .conf 文件(推荐习惯)
include /etc/nginx/conf.d/*.conf;
# Ubuntu 系统还有 sites-enabled 目录
include /etc/nginx/sites-enabled/*;
}分文件管理让每个站点配置独立维护:
# /etc/nginx/conf.d/blog.conf
server {
listen 80;
server_name blog.example.com;
# ...
}
# /etc/nginx/conf.d/api.conf
server {
listen 80;
server_name api.example.com;
# ...
}nginx -t 测试配置
# 检查语法
sudo nginx -t
# 输出展开后的完整配置(方便调试)
sudo nginx -T修改配置后必须先
nginx -t测试,再nginx -s reload生效。
目录结构
Ubuntu 的标准 Nginx 目录结构:
/etc/nginx/
├── nginx.conf # 主配置
├── mime.types # MIME 类型映射
├── modules/ # 动态模块
├── conf.d/ # 用户自定义配置(推荐)
├── sites-available/ # 站点配置(Ubuntu 风格)
├── sites-enabled/ # 启用的站点(软链到 sites-available)
└── snippets/ # 可复用的配置片段小结
- Nginx 配置是层级结构:
main→events→http→server→location。 server块定义虚拟主机(域名 + 端口),location块按 URI 匹配规则处理请求。- 推荐用
include conf.d/*.conf分文件管理各站点配置。 - 修改配置前
nginx -t测试语法,修改后nginx -s reload热加载。 nginx -T打印最终展开的完整配置,用于排查全局生效情况。
上一节:启动、停止与重载 下一节:root 与 alias
