nginx常用模块

2026-6-1 6 6/1

查看当前已编译的模块

[root@web01 ~]# nginx -V
Tengine version: Tengine/3.1.0
nginx version: nginx/1.24.0
built by gcc 7.3.0 (GCC) 
built with OpenSSL 1.1.1f  31 Mar 2020
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --add-module=modules/ngx_http_upstream_check_module

一、核心模块(默认必装)

模块 用途
ngx_core_module 全局配置:worker_processeserror_logpiduser 等
ngx_events_module 事件模型配置:worker_connectionsuse epoll 等
ngx_http_core_module HTTP 核心:serverlistenserver_namelocationrootindexerror_pagedefault_server 等

default_server 是处理“通过 IP 直接访问”的关键:可以单独定义一个 server 块来拦截所有没有匹配到域名的请求。

[root@web01 ~]# cat /etc/nginx/nginx.conf 

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


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;

    sendfile        on;   # 零拷贝,大幅提升静态文件性能
    #tcp_nopush     on;   # 合并数据包

    keepalive_timeout  65;  # 长连接超时

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

二、常用 HTTP 模块(按功能分类)

1. 访问控制

1.1.ngx_http_access_module

指令allow / deny
用途:基于 IP 的访问控制,适合后台、API 等路径限制

location /admin {
    deny  192.168.1.1;     # 拒绝单个IP
    allow 192.168.1.0/24;  # 允许网段
    deny  all;             # 拒绝其余所有
}

###从上往下匹配,匹配到谁就生效

1.2.ngx_http_rewrite_module

指令returnrewriteifset
用途:URL 重写、跳转、直接中断连接

# 域名重定向
server {
    listen 80;
    server_name old.com;
    return 301 http://new.com$request_uri;
}

# 关闭 IP 直接访问(使用 444 状态码)
server {
    listen 80 default_server;
    server_name _;
    return 444;
}
##444 是 Nginx 自定义状态码,表示直接关闭连接,不返回任何响应头。

1.3.ngx_http_auth_basic_module

指令auth_basicauth_basic_user_file

用途:HTTP 基础认证,弹窗输入用户名密码

location /private {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
###密码文件通过 htpasswd 生成:htpasswd -c /etc/nginx/.htpasswd user1

2. 目录索引与静态资源优化

2.1.ngx_http_autoindex_module

指令autoindexautoindex_exact_sizeautoindex_localtime
用途:将目录以文件列表形式展示,常用来做简易下载站

location /downloads {
    alias /data/files;
    autoindex on;
    autoindex_exact_size off;    # 显示大小 KB/MB
    autoindex_localtime on;      # 时间显示本地时间
    charset utf-8;               # 避免中文文件名乱码
}
##配合 ngx_http_referer_module 可防盗链,ngx_http_secure_link_module 可防盗链和过期。

2.2.ngx_http_gzip_module

指令gzipgzip_typesgzip_min_length 等
用途:压缩文本类响应,减少传输体积

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_min_length 1000;
gzip_comp_level 6;

##通常只压缩文本类,图片/视频本身已压缩,无需再次 gzip。

2.3.ngx_http_headers_module

指令add_headerexpires(旧用法)
用途:添加或修改 HTTP 响应头

location /static/ {
    add_header Cache-Control "public, max-age=31536000";
    add_header X-Frame-Options "SAMEORIGIN";
}

###expires 指令也属于 ngx_http_headers_module,但通常单独写:expires 30d;

2.4.ngx_http_expires_module

指令expires
用途:直接设置 Expires 和 Cache-Control 头

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
}

3. 反向代理与负载均衡

3.1.ngx_http_proxy_module

指令proxy_passproxy_set_headerproxy_cache 等
用途:将请求转发给后端服务器(HTTP)

location /api/ {
    proxy_pass http://backend_api;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

3.2.ngx_http_upstream_module

指令upstreamserver
用途:定义后端服务器组,配合 proxy_pass 做负载均衡

upstream backend_api {
    server 10.0.0.1:8080 weight=3;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080 backup;
}

server {
    location / {
        proxy_pass http://backend_api;
    }
}

3.3.ngx_http_fastcgi_module

指令fastcgi_passfastcgi_paramfastcgi_index
用途:连接 PHP-FPM 或其他 FastCGI 后端

location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

3.4.ngx_http_uwsgi_module / ngx_http_scgi_module

指令uwsgi_passscgi_pass 等
用途:分别连接 uWSGI(Python)和 SCGI 后端,用法类似 proxy_pass

4. 安全与限流

4.1.ngx_http_ssl_module

指令ssl_certificatessl_certificate_keyssl_protocols 等
用途:配置 HTTPS

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate     /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
}

4.2.ngx_http_referer_module

指令valid_referers
用途:防盗链,只允许指定来源访问资源(多用于图片、下载)

location /images/ {
    valid_referers none blocked example.com *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

4.3.ngx_http_secure_link_module

指令secure_linksecure_link_md5secure_link_secret
用途:生成带校验和/过期时间的下载链接,防止盗用

location /downloads {
    secure_link $arg_md5,$arg_expires;
    secure_link_md5 "$secure_link_expires$uri my_secret_key";
    if ($secure_link = "") { return 403; }
    if ($secure_link = "0") { return 410; }
    ...
}

###需要后端配合生成符合规则的 URL。

4.4.ngx_http_limit_conn_module

指令limit_conn_zonelimit_conn
用途:限制同一 IP 的并发连接数

http {
    limit_conn_zone $binary_remote_addr zone=conn_perip:10m;
    server {
        location / {
            limit_conn conn_perip 10;
        }
    }
}

4.5.ngx_http_limit_req_module

指令limit_req_zonelimit_req
用途:限制请求速率,防止 CC 攻击

http {
    limit_req_zone $binary_remote_addr zone=req_perip:10m rate=5r/s;
    server {
        location / {
            limit_req zone=req_perip burst=10 nodelay;
        }
    }
}

4.6.ngx_http_realip_module

指令set_real_ip_fromreal_ip_header
用途:当 Nginx 在 CDN/代理后面时,从指定头获取真实客户端 IP

set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;

5. 日志与状态监控

5.1.ngx_http_log_module

指令access_loglog_format
用途:自定义访问日志格式和路径

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;

5.2.ngx_http_stub_status_module

指令stub_status
用途:提供基础的实时状态统计(编译时需加 --with-http_stub_status_module

location /nginx_status {
    stub_status;
    allow 127.0.0.1;
    deny all;
}

6. 流媒体相关

6.1.ngx_http_mp4_module

指令mp4
用途:支持 MP4 视频的伪流(可拖拽播放),编译时加 --with-http_mp4_module

location /videos {
    mp4;
}

6.2.ngx_http_flv_module

指令flv
用途:支持 FLV 视频的流播放

location /flv {
    flv;
}

7. 内容修改

7.1.ngx_http_sub_module

指令sub_filter
用途:替换响应体中的字符串(编译时可能需 --with-http_sub_module

location / {
    sub_filter 'http://backend' 'http://frontend';
    sub_filter_once off;
}

7.2.ngx_http_addition_module

指令add_before_bodyadd_after_body
用途:在响应体前后追加内容(编译时需 --with-http_addition_module

location / {
    add_after_body /footer.html;
}

 

- THE END -

delu

6月26日18:21

最后修改:2026年6月26日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论