一、Nginx 配置文件结构
1.1 配置文件层次结构
main (全局块) # 全局配置,影响所有模块
events # 事件模块配置
http { # HTTP模块配置(最常用)
server { # 虚拟主机配置
location { # URL匹配配置
}
}
}
1.2 Location 路径匹配
语法格式:
location [修饰符] 匹配模式 {
# 配置指令
}
root 与 alias 区别:
# 1. root 指令 - 相对路径
location /images/ {
root /data/website;
# 访问 http://example.com/images/photo.jpg
# 实际文件路径:/data/website/images/photo.jpg
}
# 2. alias 指令 - 绝对路径
location /static/ {
alias /var/www/assets/;
# 访问 http://example.com/static/logo.png
# 实际文件路径:/var/www/assets/logo.png
}
# 3. root 与 alias 关键区别
# root: location 后的路径会附加到 root 指定的目录后
# alias: location 后的路径会被替换为 alias 指定的路径
# 4. alias 必须用目录分隔符结尾
location /downloads/ {
alias /home/user/files/; # 正确
}
location /docs {
alias /var/www/html/docs/; # 注意:location 和 alias 最好都以 / 结尾
}
二、HTTP 认证模块
2.1 Basic 认证配置
# 1. 创建密码文件
# htpasswd -c /etc/nginx/.htpasswd username
# 或使用openssl创建加密密码
# echo "username:$(openssl passwd -crypt password)" >> /etc/nginx/.htpasswd
# 2. nginx 配置
location /protected/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 自定义错误页面(可选)
error_page 401 = /401.html;
location = /401.html {
root /usr/share/nginx/html;
internal;
}
}
# 3. 401 错误处理
error_page 401 /error/401.html;
location /error/ {
internal;
root /usr/share/nginx/html;
}
2.2 组合认证与访问控制
location /admin/ {
# IP白名单优先
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
# 再验证用户密码
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd.admin;
# 如果认证失败返回401
error_page 401 = @auth_error;
}
location @auth_error {
return 401 "Authentication Required";
}
三、IP 访问控制模块
3.1 基础配置
# 1. 允许特定网段,拒绝其他所有
location /secure/ {
allow 192.168.16.0/24;
allow 10.10.0.0/16;
deny all;
}
# 2. 拒绝特定IP,允许其他所有
location /public/ {
deny 192.168.16.100;
deny 10.10.10.5;
allow all;
}
# 3. 逐条检查,首次匹配生效
location /api/ {
deny 1.2.3.4;
allow 192.168.0.0/16;
allow 10.0.0.0/8;
deny all; # 默认拒绝其他IP
}
# 4. 在server级别设置
server {
listen 80;
server_name example.com;
# 全局IP限制
deny 5.6.7.8;
location / {
# 继承server级别的deny规则
allow 192.168.1.0/24;
deny all;
}
}
3.2 基于geo模块的IP控制
# 创建IP地址映射
geo $block_ip {
default 0;
10.0.0.0/8 1;
192.168.0.0/16 1;
1.2.3.4 1;
}
server {
location / {
if ($block_ip) {
return 403;
}
# 其他配置
}
}
四、状态监控模块 (stub_status)
4.1 基础配置
# 1. 启用状态页(通常放在单独的location中)
server {
listen 80;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1; # 只允许本机访问
allow 192.168.1.0/24; # 或特定内网IP
deny all;
# 可选:添加认证
auth_basic "Nginx Status";
auth_basic_user_file /etc/nginx/.htpasswd.status;
}
}
# 2. 输出示例
# Active connections: 291
# server accepts handled requests
# 16630948 16630948 31070465
# Reading: 6 Writing: 179 Waiting: 106
# 3. 字段解释:
# Active connections: 当前活动连接数
# accepts: 已接受的客户端连接总数
# handled: 已处理的连接总数
# requests: 客户端请求总数
# Reading: 正在读取请求头的连接数
# Writing: 正在发送响应的连接数
# Waiting: 空闲客户端连接数
4.2 增强版状态监控
location /nginx-status {
stub_status on;
# 安全限制
allow 127.0.0.1;
deny all;
# 添加更多信息
add_header Content-Type "text/plain; charset=utf-8";
add_header Cache-Control "no-cache, no-store, must-revalidate";
# 与第三方监控集成
# 可以配合Prometheus、Zabbix等
}
五、连接限制模块
5.1 limit_conn 模块(连接数限制)
# 1. 定义共享内存区域
http {
# 定义连接限制区,命名为addr,10MB内存
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn_zone $server_name zone=perserver:10m;
# 限制每个IP的连接数
limit_conn_status 429; # 自定义返回状态码(默认503)
limit_conn_log_level error; # 记录级别
server {
# 限制每个IP最多10个连接
location /download/ {
limit_conn addr 10;
limit_rate 500k; # 限制下载速度
}
# 限制整个server的连接数
limit_conn perserver 1000;
}
}
# 2. 多维度限制示例
http {
# 按IP限制
limit_conn_zone $binary_remote_addr zone=perip:10m;
# 按server限制
limit_conn_zone $server_name zone=perserver:10m;
# 按特定变量限制(如用户ID)
limit_conn_zone $cookie_sessionid zone=peruser:10m;
server {
location /api/ {
# 每个IP最多10个连接
limit_conn perip 10;
# 每个用户最多5个连接
limit_conn peruser 5;
# server整体最多1000个连接
limit_conn perserver 1000;
}
}
}
5.2 limit_req 模块(请求频率限制)
# 限制请求速率
http {
# 定义限制区域,rate=1r/s 表示每秒1个请求
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req_zone $binary_remote_addr zone=burst:10m rate=5r/m;
server {
# 基础限制:每秒1个请求
location /api/ {
limit_req zone=one;
limit_req_status 429;
}
# 允许突发请求
location /api/burst/ {
# burst=5 允许突发5个请求
# nodelay 立即处理突发请求
limit_req zone=one burst=5 nodelay;
}
# 延迟处理突发请求
location /api/delayed/ {
# 没有nodelay,突发请求会被延迟处理
limit_req zone=one burst=5;
}
}
}
5.3 limit_rate 模块(带宽限制)
location /download/ {
# 限制下载速度为50KB/s
limit_rate 50k;
# 连接建立后10秒开始限速
limit_rate_after 10m;
# 对特定用户不限速
if ($http_cookie ~* "premium_user=true") {
set $limit_rate 0; # 0表示不限速
}
}
六、Location 匹配优先级
6.1 匹配符号及优先级
# 优先级顺序:1 → 2 → 3 → 4 → 5
# 1. = (精确匹配) - 最高优先级
location = /exact-match {
# 只匹配 /exact-match
# 不匹配 /exact-match/ 或 /exact-match/other
}
# 2. ^~ (前缀匹配) - 第二优先级
location ^~ /static/ {
# 匹配以 /static/ 开头的所有路径
# 优先级高于正则表达式
}
# 3. ~ (区分大小写正则) - 第三优先级
location ~ \.(gif|jpg|jpeg)$ {
# 匹配以 .gif, .jpg, .jpeg 结尾的URL
# 区分大小写
}
# 4. ~* (不区分大小写正则) - 第四优先级
location ~* \.(png|ico)$ {
# 匹配以 .png, .ico 结尾的URL
# 不区分大小写
}
# 5. 无符号 (普通前缀匹配) - 最低优先级
location / {
# 通用匹配,匹配所有请求
}
# 6. @ (命名location) - 不用于常规匹配
location @error {
# 内部重定向使用
return 404 "Not Found";
}
6.2 匹配规则示例
server {
# 示例配置展示优先级
# 规则1:精确匹配(优先级最高)
location = /login {
# 只匹配 http://example.com/login
return 200 "Login page";
}
# 规则2:前缀匹配(优先级次高)
location ^~ /static/ {
# 匹配 /static/css/, /static/js/ 等
root /var/www;
}
# 规则3:正则匹配(区分大小写)
location ~ /user/[0-9]+ {
# 匹配 /user/123, /user/456
proxy_pass http://backend;
}
# 规则4:正则匹配(不区分大小写)
location ~* \.(php|asp)$ {
# 匹配 .php, .PHP, .asp, .ASP 等
deny all; # 禁止访问脚本文件
}
# 规则5:普通前缀匹配(最低优先级)
location / {
# 匹配所有其他请求
try_files $uri $uri/ =404;
}
# 测试用例:
# /login → 规则1
# /static/logo.png → 规则2
# /user/123 → 规则3
# /index.PHP → 规则4
# /about → 规则5
}
6.3 优先级总结表
| 优先级 | 匹配类型 | 示例 | 说明 |
|---|---|---|---|
| 1 | 精确匹配 | location = /path | 完全匹配,最高优先级 |
| 2 | 前缀匹配(不检查正则) | location ^~ /path/ | 前缀匹配,优先级高于正则 |
| 3 | 正则匹配(区分大小写) | location ~ pattern | 正则匹配,区分大小写 |
| 4 | 正则匹配(不区分大小写) | location ~* pattern | 正则匹配,不区分大小写 |
| 5 | 普通前缀匹配 | location /path | 普通前缀匹配,最低优先级 |
| - | 命名location | location @name | 内部重定向,不用于外部匹配 |
七、错误重定向配置
7.1 基础错误页面配置
# 1. 自定义错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /404.html {
root /usr/share/nginx/html;
internal; # 只能内部访问
}
location = /50x.html {
root /usr/share/nginx/html;
internal;
}
# 2. 返回自定义响应
error_page 404 = @notfound;
error_page 403 = "403 Forbidden";
error_page 404 = /custom_404.html;
# 3. 更改响应码
error_page 404 =200 /empty.gif; # 404返回200状态码
error_page 404 =301 /index.html; # 404重定向到首页
7.2 常见错误码配置
# HTTP错误码重定向
http {
# 客户端错误
error_page 400 /error/400.html;
error_page 401 /error/401.html;
error_page 403 /error/403.html;
error_page 404 /error/404.html;
error_page 405 /error/405.html;
# 服务器错误
error_page 500 /error/500.html;
error_page 502 /error/502.html;
error_page 503 /error/503.html;
error_page 504 /error/504.html;
# 错误页面目录
location /error/ {
internal;
root /usr/share/nginx/html;
}
}
7.3 高级重定向配置
# 1. 基于域名的错误页面
server {
listen 80;
server_name api.example.com;
error_page 404 = @api_not_found;
location @api_not_found {
return 404 '{"error": "Not Found", "code": 404}';
add_header Content-Type application/json;
}
}
# 2. 维护页面重定向
# 当应用维护时,所有请求重定向到维护页面
server {
listen 80;
server_name example.com;
# 检查维护标志文件
if (-f /var/www/maintenance.flag) {
return 503;
}
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /maintenance.html break;
root /usr/share/nginx/html;
}
}
# 3. 优雅的错误处理链
location / {
# 尝试访问原始文件
try_files $uri $uri/ @backend;
# 错误处理
error_page 404 = @fallback;
error_page 502 503 504 = @backup;
}
location @backend {
proxy_pass http://backend;
proxy_intercept_errors on; # 拦截后端错误
error_page 502 503 504 = @backup;
}
location @fallback {
# 静态文件后备
try_files /cache/$uri /static/$uri =404;
}
location @backup {
# 后备服务器
proxy_pass http://backup_server;
}
7.4 完整的错误处理示例
# 完整的错误处理配置示例
http {
# 共享错误页面配置
map $status $error_page {
400 /error/bad-request.html;
401 /error/unauthorized.html;
403 /error/forbidden.html;
404 /error/not-found.html;
500 /error/internal-server-error.html;
502 /error/bad-gateway.html;
503 /error/service-unavailable.html;
504 /error/gateway-timeout.html;
default /error/generic.html;
}
server {
listen 80;
server_name www.example.com;
# 应用错误页面映射
error_page 400 401 403 404 500 502 503 504 @error_handler;
location @error_handler {
# 检查是否有对应的错误页面
if (-f /usr/share/nginx/html$error_page) {
rewrite ^ /error$error_page break;
}
# 默认错误响应
default_type text/html;
return $status "<html><body><h1>Error $status</h1></body></html>";
}
# 错误页面目录
location ^~ /error/ {
internal;
root /usr/share/nginx/html;
# 错误页面本身也应有后备
error_page 404 = /error/generic.html;
}
# 主应用
location / {
proxy_pass http://backend;
proxy_intercept_errors on;
# 后端错误也重定向到错误处理器
error_page 502 503 504 = @error_handler;
}
}
}
八、配置文件最佳实践
8.1 模块化配置
# 主配置文件:/etc/nginx/nginx.conf
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf; # 模块化配置
}
# 模块文件:/etc/nginx/conf.d/security.conf
# IP限制、限流等安全配置
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;
# 模块文件:/etc/nginx/conf.d/upstream.conf
# 上游服务器配置
upstream backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
}
# 模块文件:/etc/nginx/sites-available/example.com
server {
listen 80;
server_name example.com;
include conf.d/security-rules.conf;
location / {
proxy_pass http://backend;
}
}
8.2 调试与日志
# 调试配置
http {
# 调试日志
error_log /var/log/nginx/error.log debug;
# 自定义访问日志格式
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 buffer=32k flush=5s;
# 特定location的详细日志
location /debug/ {
access_log /var/log/nginx/debug.log main;
error_log /var/log/nginx/debug.error.log debug;
}
}
总结
核心要点回顾:
- 配置文件结构:main → events → http → server → location
- Location匹配优先级:= > ^~ > ~ > ~* > 无符号
- 安全模块:认证、IP限制、连接限制协同工作
- 监控模块:stub_status 提供基本的性能监控
- 错误处理:灵活的错误页面和重定向配置
实用配置技巧:
# 1. 综合示例:安全的API端点
location /api/ {
# 安全限制
allow 10.0.0.0/8;
deny all;
# 认证
auth_basic "API Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 限流
limit_req zone=api_limit burst=20 nodelay;
limit_conn perip 10;
# 代理
proxy_pass http://backend_api;
# 错误处理
proxy_intercept_errors on;
error_page 502 503 504 = @api_error;
}
# 2. 静态文件服务优化
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d; # 缓存30天
add_header Cache-Control "public, immutable";
# 安全考虑,防止执行
location ~ \.php$ {
deny all;
}
}
# 3. 维护模式开关
set $maintenance 0;
if (-f /etc/nginx/maintenance.flag) {
set $maintenance 1;
}
location / {
if ($maintenance = 1) {
return 503;
}
# 正常处理
}
error_page 503 @maintenance;
location @maintenance {
rewrite ^ /maintenance.html break;
root /usr/share/nginx/html;
}
这份笔记涵盖了Nginx最常用的模块和配置技巧,可根据实际需求组合使用这些配置。
Comments NOTHING