文章

nginx学习_HTTP过滤模块

http模块整体流程:

Image

HTTP请求处理流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
preaccess阶段
    -->>    limit_req zone=req_one
            bust=120;
            limit_conn c_zone 1;
access阶段
    -->>    satisfy any;
            allow 192.168.11.00/32;
            auth_basic_user_file
            access.pass;
concat阶段
header过滤模块
发送HTTP头部 有先后顺序: image图像做缩略图处理 -->>gzip压缩
    -->>    image_filter resize 500 400;
            gzip on;
            
body过滤模块
发送HTTP包体

1. sub模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
功能:   将响应中的指定字符串 替换 替换成新的字符串, 默认替换时忽略大小写
模块:   ngx_http_sub_filter_module
            默认未编译进nginx
        编译: --with-http_sub_module 启用

指令:	sub_filter string replacement;      # string: 要替换的字符串; replacement: 替换之后的字符串
默认:	一
可以出现在:	http, server, location

指令:	sub_fllter_last_modified on | off;  # 是否要返回修改之前的内容
默认:	sub filter last modified off;
可以出现在:	http, server, location

指令:	sub_filter_once on | off;       # 是否只替换一次,off: 会扫描全部的body 将匹配的字符全部替换
默认:	subfilteronce on;
可以出现在:	http, server, location

指令:	sub_filter_types mime-type      # 只针对 ** 类型的响应进行替换
默认:	sub filter types text/html;     # 默认针对 html响应进行替换, ~ * : 将所有类型的响应进行替换
可以出现在:	http, server, location

eg:
server {
    listen 15638;
    server_name www.fscloude.cn;

    root /var/www/test/;
    error_log logs/concat_test.log debug;

    location / {
        sub_filter  'Nginx.oRg' $host/nginx;
        #sub_filter 'nginX.cOm' '$host/nginx';
        sub_filter_once on;
        #sub_filter_once off;
        sub_filter_last_modified off;
        #sub_filter_last_modified on;
    }
}

2. addition模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
功能:   在响应前或者响应后增加内容, 增加方式是通过新增子请求的响应完成的
模块:   ngx_http_addition_filter_module
        默认未编译进 nginx
        编译 --with-http_addition_module 启用

指令: add_before_body url;      #在请求body之前 使用 url 子请求
默认: -
可以出现在: http, server, location

指令: add_after_body url;       #在请求body之后 使用 url 子请求
默认: -
可以出现在: http, server, location

指令: addition_types mime_type ...;
默认: addition_types text/htmll
可以出现在: http, server, location



eg:
    
server {
    listen 15639;
    server_name www.fscloude.cn;

    root /var/www/test/;
    error_log logs/concat_test.log info;

    location / {            
        add_before_body /before_action;
        add_after_body /after_action;
        addition_types *;
    }

    location /before_action {
        return 200 'before\n';
    }

    location /after_action {
        return 200 'after\n';
    }
}

本文由作者按照 CC BY 4.0 进行授权