Nginx 的 server
配置块是 Nginx 配置文件中的一个关键部分,用于定义虚拟主机。每个 server
块可以包含多个 location
块和其他指令,以处理特定的请求。下面是对 server
配置块的详细解释:
一 server
配置块的基本结构http {
# 其他全局配置
server {
# 服务器配置
}
# 可以有多个 server 块
}
二 server
配置块中的常见指令listen
listen 80; # 监听所有接口的 80 端口
listen 192.168.1.1:80; # 监听特定 IP 地址的 80 端口
server_name
server_name example.com www.example.com;
root
和 alias
root
:设置网站根目录。
root /var/www/html;
alias
:为特定位置设置别名。
location /images/ {
alias /data/images/;
}
生产常用技巧:
使用 alias 的安全性
alias 指令通过替换请求 URI 的部分来直接映射到文件系统中的一个特定目录。这种方式可以有效防止目录遍历攻击,因为它不会保留 URI 中的路径结构。
示例:
假设你有以下目录结构:
/var/www/
├── static
│ └── logo.png
└── images
└── banner.jpg
配置如下:
server {
listen 80;
server_name example.com;location /static/ {
alias /var/www/static/;
}location /images/ {
alias /var/www/images/;
}
}
请求 /static/logo.png 会映射到 /var/www/static/logo.png。
请求 /static/../images/banner.jpg 不会被解析为 /var/www/images/banner.jpg,而是会返回 404 错误。
这是因为 alias 会将 /static/ 替换为 /var/www/static/,而不会保留 URI 中的其他部分。因此,/static/../images/banner.jpg 实际上会被解析为 /var/www/static/../images/banner.jpg,这在文件系统中是无效的路径,Nginx 会返回 404 错误。
使用 root 的潜在风险
root 指令将请求的 URI 附加到 root 指定的路径后面。这种方式可能会导致目录遍历攻击,因为 URI 中的路径结构会被保留。
示例:
假设你有相同的目录结构,并且配置如下:
server {
listen 80;
server_name example.com;location /static/ {
root /var/www/;
}location /images/ {
root /var/www/;
}
}
请求 /static/logo.png 会映射到 /var/www/static/logo.png。
请求 /static/../images/banner.jpg 会被解析为 /var/www/static/../images/banner.jpg,这在文件系统中是有效的路径,指向 /var/www/images/banner.jpg。
这种情况下,恶意用户可以通过构造特定的 URL 来访问服务器上的其他文件,从而可能导致敏感信息泄露或其他安全问题。如何防止目录遍历攻击
即使使用 root 指令,也可以通过一些额外的配置来防止目录遍历攻击。以下是一些常用的方法:使用 try_files 指令:
location /static/ {
root /var/www/;
try_files $uri =404;
}
这样,如果请求的文件不存在,Nginx 会返回 404 错误,而不是尝试访问其他路径。
使用 internal 关键字:
location /internal/ {
internal; # 只允许内部重定向
root /var/www/internal/;
}
这样,只有内部重定向(如 rewrite 或 proxy_pass)才能访问这个位置,外部请求会被拒绝。
限制访问的文件类型:
location /static/ {
root /var/www/;
if ($request_uri ~* \.(php|pl|py|sh|cgi)$) {
return 403;
}
}
这样,可以防止访问特定类型的文件,例如脚本文件。
使用 location 块进行更精细的控制:
location /static/ {
root /var/www/;
location ~* \..*/.*\.php$ { # 匹配以 . 开头的路径并包含 .php 的请求
deny all;
}
}
index
index index.html index.htm;
location
location / {
# 处理根路径
}
location /api/ {
# 处理 /api/ 路径下的请求
}
location ~ \.php$ {
# 处理 PHP 文件
}
proxy_pass
location /api/ {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
fastcgi_pass
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
error_page
error_page 404 /404.html;
location = /404.html {
internal;
}
access_log
和 error_log
access_log
:记录访问日志。
access_log /var/log/nginx/access.log main;
error_log
:记录错误日志。
error_log /var/log/nginx/error.log warn;
client_max_body_size
client_max_body_size 10m; # 设置最大上传文件大小为 10MB
server
配置块示例以下是一个完整的 server
配置块示例,展示了如何配置一个简单的 Web 服务器,并处理静态文件、PHP 文件以及反向代理到后端 API 服务。
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;
error_log /var/log/nginx/error.log warn;
sendfile 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;
}
# 处理 PHP 文件
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
# 反向代理到后端 API 服务
location /api/ {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 自定义错误页面
error_page 404 /404.html;
location = /404.html {
internal;
}
}
}
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
location / { try_files $uri $uri/ =404; }
location ~ \.php$ { ... }
location /api/ { ... }
error_page 404 /404.html;
在 Nginx 中,server
块的匹配顺序是基于请求的 Host
头和监听端口进行的。Nginx 会按照一定的规则来决定哪个 server
块应该处理当前的请求。以下是详细的匹配顺序和规则:
首先,Nginx 会根据请求的端口号来选择合适的 server
块。例如,如果客户端请求的是 80 端口,那么 Nginx 会查找所有 listen 80;
的 server
块。
server_name
匹配在找到合适的端口后,Nginx 会进一步根据 Host
头(即 server_name
)来选择具体的 server
块。server_name
的匹配顺序如下:
精确匹配:
server_name
。server_name
是 example.com
,并且请求的 Host
头也是 example.com
,则这个 server
块会被选中。通配符匹配:
server_name
。server_name *.example.com
会匹配 sub.example.com
。server_name example.*
会匹配 example.com
和 example.net
。正则表达式匹配:
server_name
。server_name ~^(www\.)?example\.com$
会匹配 example.com
和 www.example.com
。默认服务器:
server
块。server
块是在指定端口上第一个定义的 server
块,或者显式指定了 default_server
参数的 server
块。server {
listen 80 default_server;
server_name _;
# 其他配置
}
假设你有以下 Nginx 配置文件:
http {
# 第一个 server 块
server {
listen 80;
server_name example.com;
root /var/www/example;
location / {
try_files $uri $uri/ =404;
}
}
# 第二个 server 块
server {
listen 80;
server_name www.example.com;
root /var/www/www_example;
location / {
try_files $uri $uri/ =404;
}
}
# 第三个 server 块
server {
listen 80 default_server;
server_name _;
root /var/www/default;
location / {
try_files $uri $uri/ =404;
}
}
# 第四个 server 块
server {
listen 80;
server_name *.example.com;
root /var/www/wildcard;
location / {
try_files $uri $uri/ =404;
}
}
# 第五个 server 块
server {
listen 80;
server_name ~^(www\.)?example\.com$;
root /var/www/regex;
location / {
try_files $uri $uri/ =404;
}
}
}
请求 http://example.com/
:
Host
头为 example.com
,精确匹配第一个 server
块。/var/www/example
作为根目录。请求 http://www.example.com/
:
Host
头为 www.example.com
,精确匹配第二个 server
块。/var/www/www_example
作为根目录。请求 http://sub.example.com/
:
Host
头为 sub.example.com
,匹配第四个 server
块(通配符匹配)。/var/www/wildcard
作为根目录。请求 http://example.net/
:
Host
头为 example.net
,没有任何匹配项,选择默认服务器(第三个 server
块)。/var/www/default
作为根目录。请求 http://www.sub.example.com/
:
Host
头为 www.sub.example.com
,正则表达式匹配第五个 server
块。/var/www/regex
作为根目录。在 Nginx 中,location
块的匹配顺序是基于请求 URI 的,并且遵循一定的优先级规则。Nginx 会按照特定的顺序来选择最合适的 location
块来处理请求。以下是 location
块的匹配顺序和规则:
location
块中的字符串,则该 location
块会被选中。location = /exact {
# 处理精确匹配 /exact 的请求
}
location
块中的字符串开头,则该 location
块会被选中。location /prefix/ {
# 处理以 /prefix/ 开头的请求
}
location
块,按配置文件中的顺序进行匹配。第一个匹配成功的 location
块会被选中。location ~ /regex/ {
# 处理匹配正则表达式 /regex/ 的请求
}
^~
的前缀匹配:如果请求的 URI 以某个 location
块中的字符串开头,并且该 location
块使用了 ^~
,则该 location
块会被选中,即使后面有更具体的正则表达式匹配。location ^~ /special-prefix/ {
# 处理以 /special-prefix/ 开头的请求,忽略后面的正则表达式匹配
}
=
):优先级最高,完全匹配 URI。^~
):次高优先级,匹配 URI 前缀,并忽略后续的正则表达式匹配。~
或 ~*
):按配置文件中的顺序进行匹配,第一个匹配成功的 location
块被选中。假设你有以下 Nginx 配置文件:
server {
listen 80;
server_name example.com;
# 精确匹配
location = /exact {
root /var/www/exact;
}
# 普通前缀匹配
location /prefix/ {
root /var/www/prefix;
}
# 特殊前缀匹配
location ^~ /special-prefix/ {
root /var/www/special_prefix;
}
# 正则表达式匹配
location ~ /regex/ {
root /var/www/regex;
}
# 默认 location
location / {
root /var/www/default;
}
}
请求 http://example.com/exact
:
location = /exact
。/var/www/exact
作为根目录。请求 http://example.com/prefix/somefile.html
:
location /prefix/
。/var/www/prefix
作为根目录。请求 http://example.com/special-prefix/somefile.html
:
location ^~ /special-prefix/
。/var/www/special_prefix
作为根目录。请求 http://example.com/regex/somefile.html
:
location ~ /regex/
。/var/www/regex
作为根目录。请求 http://example.com/otherfile.html
:
location /
。/var/www/default
作为根目录。ngx_http_core_module
- 核心模块listen
:定义服务器监听的端口和地址。server_name
:定义虚拟主机的名称。location
:定义如何处理不同 URL 路径的请求。root
和 alias
:定义文档根目录或别名。index
:定义默认的索引文件。try_files
:尝试按顺序查找多个文件,并返回第一个找到的文件。server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
ngx_http_proxy_module
- 反向代理模块proxy_pass
:指定后端服务器的地址。proxy_set_header
:设置传递给后端服务器的请求头。proxy_buffering
:开启或关闭缓冲。proxy_cache
:启用缓存。proxy_connect_timeout
和 proxy_read_timeout
:设置连接和读取超时时间。server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://backend_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
}
}
ngx_http_fastcgi_module
- FastCGI 模块fastcgi_pass
:指定 FastCGI 服务器的地址。fastcgi_param
:设置传递给 FastCGI 服务器的参数。fastcgi_index
:指定默认的 FastCGI 脚本。fastcgi_buffers
和 fastcgi_buffer_size
:设置缓冲区大小。server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
ngx_http_rewrite_module
- 重写模块rewrite
:根据正则表达式重写 URI。return
:返回特定的状态码并可选地重定向到其他 URL。if
:根据条件执行特定的操作。break
和 last
:控制重写过程的流程。server {
listen 80;
server_name example.com;
location /oldpath/ {
rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
}
location / {
if ($request_uri ~* "^/legacy/") {
return 301 http://example.com/new$uri;
}
}
}
ngx_http_ssl_module
- SSL 模块ssl on;
或 listen 443 ssl;
:启用 SSL。ssl_certificate
和 ssl_certificate_key
:指定 SSL 证书和私钥的路径。ssl_protocols
:指定支持的 SSL/TLS 协议版本。ssl_ciphers
:指定使用的加密套件。ssl_session_cache
:启用 SSL 会话缓存。server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location / {
root /var/www/html;
index index.html;
}
}
假设你已经从 Let's Encrypt 或其他受信任的 CA 获取了 SSL 证书,并将它们保存在 /etc/nginx/ssl/
目录下:
example.com.crt
- 服务器证书example.com.key
- 私钥ca_bundle.crt
- CA 捆绑包(如果需要)为了增强安全性,建议生成一个强大的 Diffie-Hellman 参数文件:
sudo openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048
编辑 Nginx 配置文件(通常是 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/default.conf
),添加或修改以下内容:
在 http
块中添加全局 SSL 和 HTTP/2 配置:
http {
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 全局 SSL 配置
ssl_protocols TLSv1.2 TLSv1.3; # 只启用现代的 TLS 协议
ssl_prefer_server_ciphers on; # 优先使用服务器端的加密套件
ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_session_cache shared:SSL:10m; # 启用会话缓存
ssl_session_timeout 10m; # 会话超时时间
ssl_dhparam /etc/nginx/ssl/dhparam.pem; # Diffie-Hellman 参数文件
ssl_stapling on; # 启用 OCSP Stapling
ssl_stapling_verify on; # 验证 OCSP 响应
resolver 8.8.8.8 8.8.4.4 valid=300s; # 使用 Google 的 DNS 服务器
# HTTP/2 配置
http2_max_field_size 10k; # 设置 HTTP/2 请求头的最大大小
http2_max_header_size 16k; # 设置 HTTP/2 请求头总大小的最大值
}
在 server
块中配置 HTTPS 和 HTTP/2:
server {
listen 80;
server_name example.com www.example.com;
# 将 HTTP 请求重定向到 HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2; # 监听 443 端口并启用 SSL 和 HTTP/2
server_name example.com www.example.com;
# SSL 证书和私钥路径
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_trusted_certificate /etc/nginx/ssl/ca_bundle.crt; # 如果有 CA 捆绑包
# 强制 HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 安全头
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'";
# 日志配置
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
# 根目录和索引文件
root /var/www/html;
index index.html index.htm;
# 默认位置块
location / {
try_files $uri $uri/ =404;
}
# 静态资源
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_proxied any;
# Brotli 压缩(如果已编译支持)
brotli on;
brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
brotli_comp_level 6;
brotli_window 16k;
# 缓存控制
location ~* \.(html|htm)$ {
expires 7d;
add_header Cache-Control "public, max-age=604800";
}
# 防止点击劫持
location ~* \.(html|htm|php)$ {
add_header X-Frame-Options SAMEORIGIN;
}
# 防止 MIME 类型嗅探
location ~* \.(eot|otf|ttf|woff|woff2|svg|jpg|jpeg|png|gif|webp|ico|pdf|doc|xls|ppt|mp3|mp4|m4a|ogg|ogv|webm|swf|css|js|html|htm|xml|json)$ {
add_header X-Content-Type-Options nosniff;
}
# 防止 XSS 攻击
location ~* \.(js|css|html|htm|xml|json)$ {
add_header X-XSS-Protection "1; mode=block";
}
# 内容安全策略
location ~* \.(js|css|html|htm|xml|json)$ {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'";
}
}
在应用新的配置之前,先测试配置文件是否有语法错误:
sudo nginx -t
如果没有错误,重启 Nginx 以应用更改:
sudo systemctl restart nginx
X-Frame-Options
、X-Content-Type-Options
、X-XSS-Protection
和 Referrer-Policy
。ngx_http_gzip_module
- Gzip 压缩模块gzip on;
:启用 Gzip 压缩。gzip_types
:指定需要压缩的 MIME 类型。gzip_comp_level
:设置压缩级别(1-9)。gzip_min_length
:设置最小响应长度以触发压缩。gzip_proxied
:设置在代理请求中启用压缩。http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_proxied any;
}
ngx_http_access_module
- 访问控制模块allow
和 deny
:允许或拒绝特定 IP 地址或子网。auth_basic
和 auth_basic_user_file
:启用基本 HTTP 认证。server {
listen 80;
server_name example.com;
location /admin/ {
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/htpasswd;
}
}
ngx_http_limit_req_module
- 请求限制模块limit_req_zone
:定义一个共享内存区域来存储状态信息。limit_req
:应用请求速率限制。http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
listen 80;
server_name example.com;
location /login/ {
limit_req zone=one burst=5 nodelay;
}
}
}
ngx_http_stub_status_module
- 状态监控模块stub_status on;
:启用状态页面。access_log off;
:关闭访问日志记录。server {
listen 80;
server_name example.com;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
ngx_http_addition_module
- 添加响应头模块add_header
:添加响应头字段。server {
listen 80;
server_name example.com;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
location / {
root /var/www/html;
index index.html;
}
}
ngx_http_autoindex_module
- 自动索引模块autoindex on;
:启用自动索引。autoindex_exact_size on;
:显示文件的确切大小(以字节为单位)。autoindex_localtime on;
:显示本地时间而不是 GMT 时间。server {
listen 80;
server_name example.com;
location /files/ {
root /var/www/html;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
}
}
ngx_http_auth_request_module
- 认证请求模块auth_request
:指定一个子请求的位置。auth_request_set
:设置变量值,基于子请求的结果。server {
listen 80;
server_name example.com;
location /auth/ {
internal;
proxy_pass http://auth_backend;
proxy_set_header X-Original-URI $request_uri;
}
location /protected/ {
auth_request /auth/;
auth_request_set $auth_status $upstream_status;
error_page 401 = @error401;
}
location @error401 {
return 401 "Unauthorized";
}
}
ngx_http_browser_module
- 浏览器兼容性模块if ($http_user_agent ~* "MSIE")
:根据用户代理字符串匹配条件。rewrite ... if=$condition;
:根据条件重写 URL。server {
listen 80;
server_name example.com;
if ($http_user_agent ~* "MSIE") {
rewrite ^(.*)$ /ie/$1 break;
}
location /ie/ {
# 特定于 IE 的配置
}
}
ngx_http_cache_purge_module
- 缓存清除模块proxy_cache_purge
:指定清除缓存的 URL 路径。server {
listen 80;
server_name example.com;
location /purge/ {
allow 192.168.1.0/24;
deny all;
proxy_cache_purge cache_zone "$scheme$request_method$host$request_uri";
}
location / {
proxy_pass http://backend;
proxy_cache cache_zone;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
ngx_http_dav_module
- WebDAV 模块dav_methods
:指定允许的 WebDAV 方法。dav_access
:设置 WebDAV 的访问权限。create_full_put_path
:自动创建 PUT 请求所需的完整路径。server {
listen 80;
server_name example.com;
location /dav/ {
root /var/www/dav;
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
}
ngx_http_empty_gif_module
- 空 GIF 模块empty_gif
:定义空 GIF 的位置。server {
listen 80;
server_name example.com;
location = /empty.gif {
empty_gif;
}
}
ngx_http_flv_module
- FLV 视频流模块flv
:启用 FLV 流。server {
listen 80;
server_name example.com;
location /videos/ {
root /var/www/videos;
flv;
}
}
ngx_http_geo_module
- 地理定位模块geo
:定义地理定位规则。default
:设置默认值。http {
geo $country {
default US;
192.168.1.0/24 CN;
10.0.0.0/8 RU;
}
server {
listen 80;
server_name example.com;
location / {
set $message "Welcome from the United States!";
if ($country = CN) {
set $message "欢迎来自中国!";
}
if ($country = RU) {
set $message "Добро пожаловать из России!";
}
return 200 $message;
}
}
}
ngx_http_gunzip_module
- 解压模块gunzip on;
:启用解压缩。server {
listen 80;
server_name example.com;
location /compressed/ {
proxy_pass http://backend;
gunzip on;
}
}
ngx_http_headers_module
- 响应头模块add_header
:添加响应头。more_clear_headers
和 more_set_headers
:使用第三方模块 headers_more
来清除或设置多个响应头。server {
listen 80;
server_name example.com;
add_header X-Custom-Header "Custom Value";
more_clear_headers 'X-Powered-By';
more_set_headers 'Strict-Transport-Security: max-age=31536000; includeSubDomains';
location / {
root /var/www/html;
index index.html;
}
}
ngx_http_limit_conn_module
- 连接限制模块limit_conn_zone
:定义一个共享内存区域来存储状态信息。limit_conn
:应用连接限制。http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name example.com;
location / {
limit_conn addr 10; # 每个 IP 地址最多 10 个并发连接
}
}
}
ngx_http_map_module
- 映射模块map
:定义映射规则。default
:设置默认值。http {
map $http_user_agent $is_mobile {
default 0;
"~*android|iphone|ipad" 1;
}
server {
listen 80;
server_name example.com;
location / {
if ($is_mobile) {
return 301 http://m.example.com$request_uri;
}
}
}
}
ngx_http_memcached_module
- Memcached 模块memcached_pass
:指定 Memcached 服务器的地址。memcached_connect_timeout
和 memcached_read_timeout
:设置连接和读取超时时间。server {
listen 80;
server_name example.com;
location /memcached/ {
set $memcached_key $uri;
memcached_pass 127.0.0.1:11211;
memcached_connect_timeout 100ms;
memcached_read_timeout 100ms;
}
}
ngx_http_proxy_protocol_module
- PROXY 协议模块proxy_protocol on;
:启用 PROXY 协议。server {
listen 80 proxy_protocol;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
}
}
ngx_http_random_index_module
- 随机索引模块random_index on;
:启用随机索引。server {
listen 80;
server_name example.com;
location /images/ {
root /var/www/html;
random_index on;
}
}
ngx_http_realip_module
- 真实 IP 模块set_real_ip_from
:指定信任的网络范围。real_ip_header
:指定用于提取真实 IP 的头字段。http {
set_real_ip_from 192.168.1.0/24;
real_ip_header X-Forwarded-For;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
ngx_http_referer_module
- 引用者模块valid_referers
:定义有效的引用者。if ($invalid_referer)
:根据无效引用者进行操作。server {
listen 80;
server_name example.com;
location /protected/ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
}
ngx_http_rewrite_module
- 重写模块(补充)rewrite
和 return
指令外,还可以使用 if
条件语句进行复杂的逻辑判断。if
:根据条件执行特定的操作。set
:设置变量。server {
listen 80;
server_name example.com;
if ($request_uri ~* "\.(gif|jpg|png)$") {
set $image_request 1;
}
location / {
if ($image_request) {
expires 30d;
}
root /var/www/html;
}
}
ngx_http_split_clients_module
- 客户端拆分模块split_clients
:定义拆分规则。http {
upstream backend_a {
server 192.168.1.1;
}
upstream backend_b {
server 192.168.1.2;
}
split_clients "${remote_addr}" $upstream_group {
50% "backend_a";
* "backend_b";
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://$upstream_group;
}
}
}
ngx_http_upstream_module
- 上游模块upstream
:定义服务器组。server
:指定具体的服务器。weight
:设置服务器的权重。max_fails
和 fail_timeout
:设置失败次数和超时时间。http {
upstream backend {
server 192.168.1.1 weight=3;
server 192.168.1.2;
server 192.168.1.3 backup;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}