Nginx 的配置文件采用分块式结构,主要由指令和上下文块(Context)组成,采用类似 C 语言的 {}
语法划分作用域。以下是核心结构和关键组成部分:
/etc/nginx/nginx.conf
(Linux)或 nginx/conf/nginx.conf
(Windows)include
指令加载其他文件(如 sites-enabled/*.conf
)。{}
的指令。user nginx; # 运行用户
worker_processes auto; # 工作进程数(通常设为CPU核心数)
error_log /var/log/nginx/error.log warn; # 错误日志路径和级别
pid /var/run/nginx.pid; # 进程PID文件路径
events {
worker_connections 1024; # 每个进程的最大连接数
}
http {
include /etc/nginx/mime.types; # 引入MIME类型定义文件
default_type application/octet-stream; # 默认响应类型
sendfile on; # 启用高效文件传输模式
keepalive_timeout 65; # 长连接超时时间(秒)
# 服务器块(虚拟主机配置)
server {
listen 80; # 监听端口
server_name example.com; # 域名或IP
root /var/www/html; # 网站根目录
location / { # URL路径匹配规则
index index.html;
}
}
}
mail {
server {
listen 25;
protocol smtp;
}
}
http
块可包含多个 server
)。server {
listen 80;
server_name example.com www.example.com;
access_log /var/log/nginx/example.com.access.log;
location / {
proxy_pass http://backend_server; # 反向代理到后端
}
}
location /images/ {
alias /data/static/images/; # 路径别名(替换匹配部分)
expires 30d; # 静态文件缓存时间
}
location ~ \.php$ { # 正则匹配PHP文件
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
upstream backend {
server 10.0.0.1:8080 weight=3; # 权重负载均衡
server 10.0.0.2:8080;
keepalive 32; # 长连接数
}
指令 | 作用 |
---|---|
listen |
监听端口(如 80 或 443 ssl ) |
server_name |
匹配的域名(支持通配符 * ) |
root / alias |
文件路径映射 |
proxy_pass |
反向代理到后端 |
rewrite |
URL重写规则 |
ssl_certificate |
HTTPS证书路径 |
# 检查语法是否正确
nginx -t
# 重新加载配置(不中断服务)
nginx -s reload
include
拆分配置(如分离 server
配置)。worker_processes
、gzip
等通常在 http
块顶部定义。如果需要具体场景的配置示例(如 HTTPS、负载均衡),可以进一步说明!