页面内容
# NGINX HTTP 功能模块详解
本文档详细介绍 NGINX 常用的 HTTP 功能模块及其配置方法。
---
## 1. ngx_http_access_module (访问控制模块)
### 概述
ngx_http_access_module 模块用于限制对某些客户端地址的访问,提供简单的基于 IP 的访问控制功能。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `allow` | `allow address \| CIDR \| unix: \| all;` | - | 允许指定地址访问 | http, server, location, limit_except |
| `deny` | `deny address \| CIDR \| unix: \| all;` | - | 拒绝指定地址访问 | http, server, location, limit_except |
### 配置示例
```nginx
# 拒绝单个 IP
location /admin/ {
deny 192.168.1.1;
allow 192.168.1.0/24;
deny all;
}
# 只允许内网访问管理后台
server {
listen 80;
server_name admin.example.com;
location / {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
deny all;
proxy_pass http://backend;
}
}
# 拒绝特定网段,允许其他
location /api/ {
deny 192.168.1.0/24;
allow all;
}
```
### 应用场景
- **管理后台保护**:限制只有内网 IP 可以访问管理后台
- **API 访问控制**:限制特定 IP 才能调用敏感 API
- **防御恶意 IP**:封禁已知的攻击源 IP 地址
---
## 2. ngx_http_auth_basic_module (基础认证模块)
### 概述
ngx_http_auth_basic_module 模块允许使用 HTTP 基本认证协议验证用户名和密码,提供简单的用户名/密码访问控制。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `auth_basic` | `auth_basic string \| off;` | `off` | 启用基本认证并设置提示信息 | http, server, location, limit_except |
| `auth_basic_user_file` | `auth_basic_user_file file;` | - | 指定密码文件路径 | http, server, location, limit_except |
### 配置示例
```nginx
# 基本认证配置
location /admin/ {
auth_basic "Administrator's Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
# 生成密码文件
# 使用 htpasswd 工具
# htpasswd -c /etc/nginx/.htpasswd username
# 使用 openssl 生成
# printf "username:$(openssl passwd -crypt password)\n" >> /etc/nginx/.htpasswd
# 多区域不同认证
server {
listen 80;
server_name example.com;
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/admin.htpasswd;
proxy_pass http://backend;
}
location /api/private/ {
auth_basic "API Access";
auth_basic_user_file /etc/nginx/api.htpasswd;
proxy_pass http://api_backend;
}
}
```
### 密码文件格式
```
# /etc/nginx/.htpasswd
username1:encrypted_password1
username2:encrypted_password2
```
### 应用场景
- **开发环境保护**:为开发环境添加简单密码保护
- **内部文档访问**:限制内部文档仅供授权用户访问
- **简单后台管理**:小型项目的后台管理保护
---
## 3. ngx_http_auth_request_module (请求认证模块)
### 概述
ngx_http_auth_request_module 模块通过子请求实现基于外部服务的认证,允许向认证服务发送请求验证用户身份。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `auth_request` | `auth_request uri \| off;` | `off` | 启用认证请求并指定认证 URI | http, server, location |
| `auth_request_set` | `auth_request_set $variable value;` | - | 从认证响应中设置变量 | http, server, location |
### 配置示例
```nginx
# 基础认证代理配置
location /private/ {
auth_request /auth;
auth_request_set $auth_status $upstream_status;
proxy_pass http://backend;
}
# 认证服务 location
location = /auth {
internal;
proxy_pass http://auth-server/verify;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Original-Method $request_method;
}
# 完整示例:JWT 验证
server {
listen 80;
server_name api.example.com;
location /api/ {
auth_request /auth_jwt;
auth_request_set $auth_user $upstream_http_x_user_id;
auth_request_set $auth_roles $upstream_http_x_roles;
proxy_set_header X-User-ID $auth_user;
proxy_set_header X-Roles $auth_roles;
proxy_pass http://api_backend;
}
location = /auth_jwt {
internal;
proxy_pass http://auth-service/validate;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Authorization $http_authorization;
proxy_set_header X-Real-IP $remote_addr;
}
}
# 带缓存的认证
location /protected/ {
auth_request /auth;
auth_request_set $auth_cache $upstream_http_x_auth_cache;
proxy_cache_key "$cookie_session_id$request_method$host$request_uri";
proxy_pass http://backend;
}
```
### 应用场景
- **OAuth/JWT 认证**:集成 OAuth2 或 JWT 认证服务
- **集中式认证**:统一认证中心验证用户身份
- **多系统单点登录**:实现跨系统的统一认证
- **自定义认证逻辑**:实现复杂的认证业务逻辑
---
## 4. ngx_http_autoindex_module (自动索引模块)
### 概述
ngx_http_autoindex_module 模块用于自动生成目录列表页面,当请求以 `/` 结尾时展示目录内容。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `autoindex` | `autoindex on \| off;` | `off` | 启用自动目录列表 | http, server, location |
| `autoindex_exact_size` | `autoindex_exact_size on \| off;` | `on` | 显示精确文件大小 | http, server, location |
| `autoindex_format` | `autoindex_format html \| xml \| json \| jsonp;` | `html` | 目录列表格式 | http, server, location |
| `autoindex_localtime` | `autoindex_localtime on \| off;` | `off` | 使用本地时间显示 | http, server, location |
### 配置示例
```nginx
# 基本目录浏览
location /files/ {
root /data/public;
autoindex on;
}
# 优化显示格式
location /downloads/ {
root /data/downloads;
autoindex on;
autoindex_exact_size off; # 显示 KB/MB 而非字节
autoindex_localtime on; # 本地时间格式
}
# JSON 格式 API
location /api/files/ {
root /data/public;
autoindex on;
autoindex_format json;
}
# 文件服务器配置
server {
listen 80;
server_name files.example.com;
location / {
root /var/www/files;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 美化目录页面(可选)
add_header X-Robots-Tag "noindex, nofollow";
}
}
```
### 应用场景
- **文件下载站**:提供文件目录浏览和下载功能
- **文档服务器**:文档资源的目录化访问
- **镜像站点**:软件镜像的目录展示
- **内部资源共享**:企业内部文件共享访问
---
## 5. ngx_http_browser_module (浏览器检测模块)
### 概述
ngx_http_browser_module 模块用于根据 User-Agent 请求头创建变量,标识是否为古老或现代浏览器。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `ancient_browser` | `ancient_browser string ...;` | - | 定义古老浏览器标识 | http, server, location |
| `ancient_browser_value` | `ancient_browser_value value;` | `1` | 古老浏览器变量值 | http, server, location |
| `modern_browser` | `modern_browser browser version \| unlisted;` | - | 定义现代浏览器 | http, server, location |
| `modern_browser_value` | `modern_browser_value value;` | `0` | 现代浏览器变量值 | http, server, location |
### 配置示例
```nginx
# 定义古老浏览器
http {
ancient_browser "MSIE 6.0";
ancient_browser "MSIE 5.5";
ancient_browser "MSIE 5.0";
ancient_browser "MSIE 4.0";
# 定义现代浏览器
modern_browser msie 7.0;
modern_browser opera 9.0;
modern_browser safari 3.0;
modern_browser firefox 3.0;
modern_browser chrome 1.0;
server {
listen 80;
location / {
# 古老浏览器重定向
if ($ancient_browser) {
rewrite ^ /browser-not-supported.html last;
}
# 现代浏览器正常访问
proxy_pass http://backend;
}
}
}
# 根据浏览器类型分配不同后端
server {
listen 80;
server_name app.example.com;
location / {
# 古老浏览器使用兼容版本
if ($ancient_browser) {
proxy_pass http://legacy_backend;
break;
}
# 现代浏览器使用标准版本
proxy_pass http://modern_backend;
}
}
# 浏览器日志记录
log_format browser '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_user_agent" ancient=$ancient_browser';
access_log /var/log/nginx/browser.log browser;
```
### 应用场景
- **浏览器兼容性提示**:检测古老浏览器提示用户升级
- **差异化服务**:为不同浏览器提供不同版本的内容
- **统计分析**:分析用户浏览器分布情况
- **功能降级**:为古老浏览器提供简化功能
---
## 6. ngx_http_charset_module (字符集模块)
### 概述
ngx_http_charset_module 模块用于将指定的字符集添加到 Content-Type 响应头,并可以在不同字符集之间转换响应内容。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `charset` | `charset charset \| off;` | `off` | 设置响应字符集 | http, server, location, if in location |
| `charset_map` | `charset_map source_charset destination_charset { ... }` | - | 定义字符集映射 | http |
| `override_charset` | `override_charset on \| off;` | `off` | 覆盖源字符集 | http, server, location, if in location |
| `source_charset` | `source_charset charset;` | - | 设置源字符集 | http, server, location, if in location |
### 配置示例
```nginx
# 基本字符集设置
server {
listen 80;
server_name example.com;
charset utf-8;
source_charset utf-8;
}
# 字符集转换
location /legacy/ {
source_charset gb2312;
charset utf-8;
}
# 字符集映射定义
http {
charset_map koi8-r utf-8 {
# 从 koi8-r 到 utf-8 的字符映射
80 E28099; # 单引号
95 E280A6; # 省略号
9A C2A0; # 不换行空格
}
}
# 不同路径不同字符集
server {
listen 80;
location /cn/ {
charset gb2312;
root /var/www/cn;
}
location /en/ {
charset utf-8;
root /var/www/en;
}
location /jp/ {
charset shift_jis;
root /var/www/jp;
}
}
# 根据来源覆盖字符集
location /api/ {
charset utf-8;
override_charset on; # 强制使用 utf-8
proxy_pass http://backend;
}
```
### 应用场景
- **多语言网站**:为不同语言设置合适的字符集
- **遗留系统兼容**:转换旧系统的非 UTF-8 编码
- **API 标准化**:统一 API 响应字符集为 UTF-8
- **字符集规范化**:确保所有响应使用正确字符集
---
## 7. ngx_http_geo_module (地理位置变量模块)
### 概述
ngx_http_geo_module 模块用于根据客户端 IP 地址创建变量,实现基于地理位置的访问控制或内容定制。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `geo` | `geo [$address] $variable { ... }` | - | 定义地理位置映射 | http |
### 配置示例
```nginx
# 基本地理位置定义
http {
geo $geo {
default unknown;
127.0.0.1 local;
192.168.1.0/24 internal;
10.0.0.0/8 internal;
1.2.3.4 china;
5.6.7.8 usa;
}
server {
listen 80;
location / {
add_header X-Geo $geo;
return 200 "Your location: $geo";
}
}
}
# 使用变量作为数据源
geo $arg_ip $geo {
default unknown;
192.168.0.0/16 local;
}
# 复杂地理位置配置
geo $geo_country {
default other;
include /etc/nginx/geo/countries.conf; # 包含外部文件
# 中国 IP 段
1.0.1.0/24 cn;
1.0.2.0/23 cn;
1.0.32.0/19 cn;
# ... 更多 IP 段
# 美国 IP 段
3.0.0.0/8 us;
4.0.0.0/8 us;
# ... 更多 IP 段
delete 127.0.0.0/16; # 删除特定范围
proxy 192.168.100.1; # 递归查询代理
proxy_recursive on; # 启用递归代理
}
# 应用示例:区域路由
server {
listen 80;
server_name example.com;
location / {
if ($geo_country = cn) {
proxy_pass http://cn_backend;
break;
}
if ($geo_country = us) {
proxy_pass http://us_backend;
break;
}
proxy_pass http://default_backend;
}
}
# 访问限制
geo $allowed {
default 0;
192.168.0.0/16 1;
10.0.0.0/8 1;
172.16.0.0/12 1;
}
server {
location /admin/ {
if ($allowed = 0) {
return 403;
}
proxy_pass http://backend;
}
}
```
### 应用场景
- **区域路由**:根据用户地区路由到不同服务器
- **地理位置限制**:限制或允许特定地区访问
- **内容定制**:根据地区显示不同内容
- **访问统计分析**:按地理位置统计访问日志
---
## 8. ngx_http_geoip_module (GeoIP 模块)
### 概述
ngx_http_geoip_module 模块使用 MaxMind GeoIP 数据库创建变量,提供基于 IP 的地理位置信息(国家、城市、坐标等)。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `geoip_country` | `geoip_country file;` | - | 指定国家数据库 | http |
| `geoip_city` | `geoip_city file;` | - | 指定城市数据库 | http |
| `geoip_org` | `geoip_org file;` | - | 指定组织数据库 | http |
| `geoip_proxy` | `geoip_proxy address \| CIDR;` | - | 定义代理服务器 | http |
| `geoip_proxy_recursive` | `geoip_proxy_recursive on \| off;` | `off` | 递归搜索代理 | http |
### 配置示例
```nginx
# 基本 GeoIP 配置
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
server {
listen 80;
location /geo {
add_header X-Country-Code $geoip_country_code;
add_header X-Country-Name $geoip_country_name;
add_header X-City $geoip_city;
add_header X-Region $geoip_region;
add_header X-Region-Name $geoip_region_name;
add_header X-Latitude $geoip_latitude;
add_header X-Longitude $geoip_longitude;
return 200 "Country: $geoip_country_name, City: $geoip_city";
}
}
}
# 代理环境配置
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_proxy 192.168.1.0/24;
geoip_proxy_recursive on;
server {
location / {
proxy_set_header X-Country $geoip_country_code;
proxy_pass http://backend;
}
}
}
# 区域限制示例
server {
listen 80;
server_name example.com;
location / {
# 禁止特定国家访问
if ($geoip_country_code = "CN") {
return 403;
}
proxy_pass http://backend;
}
}
# 多数据库配置
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
geoip_org /usr/share/GeoIP/GeoIPASNum.dat;
server {
location /api/geo {
default_type application/json;
return 200 '{
"country_code": "$geoip_country_code",
"country_name": "$geoip_country_name",
"city": "$geoip_city",
"region": "$geoip_region",
"latitude": "$geoip_latitude",
"longitude": "$geoip_longitude",
"org": "$geoip_org"
}';
}
}
}
```
### 可用变量
| 变量名 | 说明 |
|--------|------|
| `$geoip_country_code` | 两位国家代码 |
| `$geoip_country_code3` | 三位国家代码 |
| `$geoip_country_name` | 国家名称 |
| `$geoip_city` | 城市名称 |
| `$geoip_region` | 地区代码 |
| `$geoip_region_name` | 地区名称 |
| `$geoip_latitude` | 纬度 |
| `$geoip_longitude` | 经度 |
| `$geoip_postal_code` | 邮政编码 |
| `$geoip_org` | 组织/ISP 名称 |
### 应用场景
- **地理位置服务**:为应用提供用户地理位置信息
- **内容本地化**:根据国家展示不同语言/货币的内容
- **访问控制**:基于国家代码限制访问
- **CDN 优化**:根据地理位置选择最近的服务器
---
## 9. ngx_http_map_module (变量映射模块)
### 概述
ngx_http_map_module 模块用于创建变量,其值取决于其他变量的值,实现灵活的变量映射和转换。
### 核心指令
| 指令 | 语法 | 默认值 | 说明 | 上下文 |
|------|------|--------|------|--------|
| `map` | `map string $variable { ... }` | - | 定义变量映射 | http |
| `map_hash_max_size` | `map_hash_max_size size;` | `2048` | 哈希表最大大小 | http |
| `map_hash_bucket_size` | `map_hash_bucket_size size;` | `32\|64\|128` | 哈希桶大小 | http |
### 配置示例
```nginx
# 基本变量映射
http {
map $http_host $backend {
default backend_default;
example.com backend_example;
api.example.com backend_api;
"*.test.com" backend_test;
}
server {
location / {
proxy_pass http://$backend;
}
}
}
# 主机名到后端映射
map $host $backend_pool {
default http://default_backend;
"~^(? 匹配成功 其他匹配 默认内容 页面内容