Nginx 的配置文件通常位于 /etc/nginx/nginx.conf
,并通过 include
指令加载其他目录(如 /etc/nginx/conf.d/
或 /etc/nginx/sites-enabled/
)中的配置片段。以下是一个结构化指南:
核心配置结构
# 全局配置 (主上下文)
user nginx; # 运行用户和工作进程数
worker_processes auto; # 自动根据CPU核心数设置
error_log /var/log/nginx/error.log warn; # 错误日志路径和级别
pid /run/nginx.pid; # 进程ID文件# 事件模块配置
events {worker_connections 1024; # 单个工作进程最大连接数use epoll; # 高性能事件模型(Linux)
}# 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; # 优化数据包发送keepalive_timeout 65; # 长连接超时时间# 服务器块配置 (虚拟主机)server {listen 80; # 监听端口server_name example.com www.example.com; # 域名root /var/www/html; # 网站根目录index index.html index.htm; # 默认索引文件# 静态文件处理location / {try_files $uri $uri/ =404;}# 反向代理配置 (示例: 代理到Node.js应用)location /api/ {proxy_pass http://localhost:3000; # 后端地址proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}# 错误页面error_page 404 /404.html;error_page 500 502 503 504 /50x.html;}# 可包含其他配置include /etc/nginx/conf.d/*.conf;
}
常用功能配置示例
1. HTTPS 配置
server {listen 443 ssl;server_name example.com;ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;# 强制HTTP跳转HTTPSreturn 301 https://$host$request_uri;
}
2. 负载均衡
upstream backend {server backend1.example.com weight=3; # 权重server backend2.example.com;server 192.168.1.100:8080 backup; # 备用服务器
}server {location / {proxy_pass http://backend; # 指向upstream组}
}
3. 重定向与重写
# 旧域名重定向到新域名
server {listen 80;server_name old.com;return 301 https://new.com$request_uri;
}# URL重写 (美化URL)
location /blog/ {rewrite ^/blog/(.*)$ /index.php?post=$1 last;
}
4. 静态资源缓存
location ~* \.(jpg|css|js)$ {expires 30d; # 客户端缓存30天add_header Cache-Control "public";
}
5. 安全加固
# 禁止访问隐藏文件
location ~ /\. {deny all;
}# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|POST|HEAD)$) {return 405;
}
配置检查与重载
# 检查语法错误
nginx -t# 重载配置 (不中断服务)
nginx -s reload
目录结构说明
路径 | 用途 |
---|---|
/etc/nginx/nginx.conf | 主配置文件 |
/etc/nginx/conf.d/ | 自定义配置片段(推荐) |
/var/www/html | 默认网站根目录 |
/var/log/nginx/ | 日志目录 |
提示:
- 使用
include
拆分配置,便于管理。- 生产环境务必启用 HTTPS(如 Let’s Encrypt)。
- 通过
nginx -T
查看完整配置(包括所有include
)。
根据实际需求调整配置后,务必执行 nginx -t
验证语法!