之前写过nginx反代替换的教程(传送门),使用了ngx_http_substitutions_filter_module模块。不过这货只能替换同一行,具有局限性-_-#

现在一个更强大的替换模块来了……replace-filter-nginx-module

下面只翻译一下,再加个安装教程,因为我自己也没弄懂怎样玩= =

 

1.安装此模块需要先安装sregex运行库

apt-get update;apt-get install git make gcc -y  #Centos改成yum
git clone https://github.com/agentzh/sregex
cd sregex
make
make install 
cd ..
git clone https://github.com/agentzh/replace-filter-nginx-module
wget http://nginx.org/download/nginx-1.2.6.tar.gz
tar zxvf nginx-1.2.6.tar.gz
cd nginx-1.2.6
./configure --add-module=../replace-filter-nginx-module  #自行加其他编译参数
make 
make install

nginx.conf的用法举例:

location /t {
    default_type text/html;
    echo abc;
    replace_filter 'ab|abc' X;
}

location / {
    # proxy_pass/fastcgi_pass/...

    # caseless global substitution:
    replace_filter '\d+' 'blah blah' 'ig';
    replace_filter_types text/plain text/css;
}

Syntax语法:

^             匹配起始行数
$             匹配末尾行数

\A match only at beginning of stream
\z match only at end of stream

\b match a word boundary
\B match except at a word boundary

. match any char
\C match a single C-language char (octet)

[ab0-9] character classes (positive)
[^ab0-9] character classes (negative)

\d match a digit character ([0-9])
\D match a non-digit character ([^0-9])

\s match a whitespace character ([ \f\n\r\t])
\S match a non-whitespace character ([^ \f\n\r\t])

\h match a horizontal whitespace character
\H match a character that isn't horizontal whitespace

\v match a vertical whitespace character
\V match a character that isn't vertical whitespace

\w match a "word" character ([A-Za-z0-9_])
\W match a non-"word" character ([^A-Za-z0-9_])

\cK control char (example: VT)

\N match a character that isn't a newline

ab concatenation; first match a, and then b
a|b alternation; match a or b

(a) capturing parentheses
(?:a) non-capturing parantheses

a? match 1 or 0 times, greedily
a* match 0 or more times, greedily
a+ match 1 or more times, greedily

a?? match 1 or 0 times, not greedily
a*? match 0 or more times, not greedily
a+? match 1 or more times, not greedily

a{n} match exactly n times
a{n,m} match at least n but not more than m times, greedily
a{n,} match at least n times, greedily

a{n}? match exactly n times, not greedily (redundant)
a{n,m}? match at least n but not more than m times, not greedily
a{n,}? match at least n times, not greedily

 

作者信息:
Yichun "agentzh" Zhang (章亦春) [email protected]

   

已有 7 條評論

  1. Zeraba 13 年前 (2013-01-03)
    @

    你的翻译哪下面那些替换规则类似php使用正则和直接替换的感觉可惜你换了多说 不然刷评论看看你博客会不会404 嗯

    • 飛天鼠 13 年前 (2013-01-03)
      @

      不换多说不行。。。太蛋疼了。。。。

  2. JyLee 13 年前 (2013-01-01)
    @

    test

  3. 花舞花落泪 13 年前 (2013-01-01)
    @

    懒得玩反带了。。。

    • JyLee 13 年前 (2013-01-01)
      @

      不一定要反代的嘛。。。

      • 花舞花落泪 13 年前 (2013-01-01)
        @

        求带,杂弄?

        • JyLee 13 年前 (2013-01-02)
          @

          本机玩= =