Nginx 是一个高性能的HTTP和反向代理服务器,广泛用于网站托管、负载均衡和反向代理等场景。Nginx 提供了许多模块来扩展其功能。以下是一些常用的 Nginx 模块及其配置示例。
常用模块
http_gzip_module:用于压缩响应内容,减少传输数据量。http_rewrite_module:用于URL重写。http_proxy_module:用于反向代理。http_ssl_module:用于SSL/TLS加密。http_cache_purge_module:用于清除缓存。http_auth_basic_module:用于基本认证。http_limit_req_module:用于限制请求速率。http_limit_conn_module:用于限制连接数。http_log_module:用于日志记录。http_geo_module:用于基于IP地址的地理位置信息。
配置示例
1. 压缩响应内容(http_gzip_module)
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml+rss;
}
2. URL重写(http_rewrite_module)
server {
listen 80;
server_name example.com;
location /old-path {
rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
}
}
3. 反向代理(http_proxy_module)
server {
listen 80;
server_name example.com;
location /app {
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;
}
}
4. SSL/TLS加密(http_ssl_module)
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/certificate.pem;
ssl_certificate_key /path/to/privatekey.pem;
location / {
root /var/www/html;
index index.html index.htm;
}
}
5. 清除缓存(http_cache_purge_module)
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server;
proxy_cache my_cache;
proxy_cache_bypass $http_purge;
proxy_cache_methods GET HEAD;
proxy_cache_revalidate on;
proxy_cache_lock on;
proxy_cache_min_uses 1;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge my_cache $1$is_args$args;
}
}
}
6. 基本认证(http_auth_basic_module)
server {
listen 80;
server_name example.com;
location /protected {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/htpasswd;
}
}
7. 限制请求速率(http_limit_req_module)
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
listen 80;
server_name example.com;
location / {
limit_req zone=one burst=5 nodelay;
}
}
}
8. 限制连接数(http_limit_conn_module)
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name example.com;
location / {
limit_conn addr 10;
}
}
}
9. 日志记录(http_log_module)
http {
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}
10. 基于IP地址的地理位置信息(http_geo_module)
http {
geo $geo {
default 0;
192.168.1.0/24 1;
}
server {
listen 80;
server_name example.com;
location / {
if ($geo = 1) {
return 200 "Welcome from the local network!";
}
return 200 "Welcome from the internet!";
}
}
}