插件窝 干货文章 Nginx服务器的nginx-http-footer-filter模块怎么配置

Nginx服务器的nginx-http-footer-filter模块怎么配置

Footer Nginx 模块 添加 564    来源:    2025-04-21

Nginx HTTP Footer Filter 模块配置指南

nginx-http-footer-filter 是一个第三方 Nginx 模块,用于在响应的 HTML 页面底部添加自定义内容(如版权信息、统计代码等)。以下是该模块的详细配置方法:

1. 安装模块

首先需要编译安装包含此模块的 Nginx:

# 下载模块
git clone https://github.com/alibaba/nginx-http-footer-filter.git

# 编译Nginx时添加模块
./configure --add-module=/path/to/nginx-http-footer-filter
make
make install

2. 基本配置

在 Nginx 配置文件中添加以下内容:

http {
    footer_types "text/html";
    footer "$host_comment";
    footer_hostnames "example.com=Example Site;*.example.org=Test Site";
}

3. 配置参数详解

主要指令

  • footer_types: 指定哪些 MIME 类型的响应需要添加页脚

    footer_types "text/html" "text/plain";
    
  • footer: 设置要添加的页脚内容

    footer "<!-- Powered by Nginx -->";
    
  • footer_hostnames: 根据不同域名设置不同的页脚

    footer_hostnames "example.com=Example Site;test.com=Test Site";
    

高级配置

  • 使用变量动态生成页脚:

    footer "<!-- Served by $server_name at $time_local -->";
    
  • 排除特定URL:

    location /admin/ {
      footer off;
    }
    
  • 只对特定状态码添加页脚:

    footer_statuses 200 301 302;
    

4. 完整示例

http {
    footer_types "text/html";
    footer "<!-- Page generated at $time_local -->\n<!-- Powered by Nginx -->";
    footer_hostnames "example.com=Example Site;test.com=Test Site";

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            footer "<!-- Custom footer for $host -->";
        }

        location /api/ {
            footer off;  # 不添加页脚
        }
    }
}

5. 注意事项

  1. 该模块只对响应正文进行修改,不影响响应头
  2. 确保添加的内容不会破坏HTML结构(如未闭合的标签)
  3. 对于gzip压缩的响应,模块会自动解压、修改后重新压缩
  4. 性能影响:添加页脚会增加少量处理开销

6. 测试与验证

配置完成后,可以:

  1. 重载Nginx配置:

    nginx -s reload
    
  2. 使用curl测试:

    curl -i http://example.com
    
  3. 检查响应HTML底部是否包含配置的页脚内容

如需更复杂的内容注入,可以考虑结合Nginx的sub_filter模块使用。