Apache 模块 mod_substitute

Description:在响应正文上执行搜索和替换操作
Status:Extension
Module Identifier:substitute_module
Source File:mod_substitute.c
Compatibility:在 Apache HTTP Server 2.2.7 和更高版本中可用

Summary

mod_substitute提供了一种在响应主体上执行正则表达式和固定字符串替换的机制。

Substitute Directive

Description:用于过滤响应内容的模式
Syntax:Substitute s/pattern/substitution/[infq]
Context:directory, .htaccess
Override:FileInfo
Status:Extension
Module:mod_substitute

Substitute伪指令指定要应用于响应正文的搜索和替换模式。

可以通过使用以下标志的任意组合来修改模式的含义:

  • i

    • 执行不区分大小写的匹配。
  • n

    • 默认情况下,模式被视为正则表达式。使用n标志会强制将模式视为固定字符串。
  • f

    • f标志使mod_substitute变平替换的结果,以允许稍后替换发生在该边界上。这是默认值。
  • q

    • 每次替换后,q标志会导致mod_substitute不对存储桶进行展平。这可能会导致更快的响应并降低内存使用率,但仅应在一个替换的结果不可能与后续替换的模式或正则表达式匹配的情况下使用。

替换内容可能包含 Literals 文本和正则表达式反向引用

Example

<Location "/">
    AddOutputFilterByType SUBSTITUTE text/html
    Substitute "s/foo/bar/ni"
</Location>

用于分隔(或“定界”)替换字符串各个部分的字符称为“定界符”,最常见的是为此使用斜杠。

如果模式或替换包含斜杠字符,则可以使用替代定界符使指令更具可读性:

使用替代定界符的示例

<Location "/">
    AddOutputFilterByType SUBSTITUTE text/html
    Substitute "s|<BR */?>|
|i" </Location>

使用正则表达式时,可以在比较和替换中使用后向引用,如以下示例所示:

使用反向引用和捕获的示例

<Location "/">
    AddOutputFilterByType SUBSTITUTE text/html
    # "foo=k,bar=k" -> "foo/bar=k"
    Substitute "s|foo=(\w+),bar=\1|foo/bar=$1|"
</Location>

mod_substitute的一种常见使用情况是前端服务器代理请求到后端服务器,该服务器返回带有带有硬编码嵌入式 URL 的 HTML,这些 URL 引用了后端服务器。这些网址不适用于最终用户,因为后端服务器无法访问。

在这种情况下,mod_substitute可用于将这些 URL 重写为可以从前端使用的内容:

重写嵌入在代理内容中的 URL

ProxyPass        "/blog/" "http://internal.blog.example.com/"
ProxyPassReverse "/blog/" "http://internal.blog.example.com/"

Substitute "s|http://internal.blog.example.com/|http://www.example.com/blog/|i"

ProxyPassReverse修改了后端服务器发送的任何Location(重定向)Headers,在此示例中,Substitute也通过修复 HTML 响应来解决其余问题。

SubstituteInheritBefore Directive

Description:更改继承模式的合并 Sequences
Syntax:SubstituteInheritBefore on|off
Default:SubstituteInheritBefore off
Context:directory, .htaccess
Override:FileInfo
Status:Extension
Module:mod_substitute
Compatibility:在 httpd 2.4.17 及更高版本中可用

是先应用继承的Substitute模式(on),还是在当前上下文的后一个(off)之后应用。 SubstituteInheritBefore本身是继承的,因此继承它的上下文(未指定自己的SubstituteInheritBefore值的上下文)将应用最接近的定义合并 Sequences。

SubstituteMaxLineLength Directive

Description:设置最大行大小
Syntax:SubstituteMaxLineLength bytes(b|B|k|K|m|M|g|G)
Default:SubstituteMaxLineLength 1m
Context:directory, .htaccess
Override:FileInfo
Status:Extension
Module:mod_substitute
Compatibility:在 httpd 2.4.11 及更高版本中可用

mod_substitute处理的最大行大小被限制为限制内存使用。可以使用SubstituteMaxLineLength配置限制。该值可以作为字节数给出,并且可以后跟一个字母bBkKmMgG作为后缀,以分别提供字节,千字节,兆字节或千兆字节的大小。

Example

<Location "/">
    AddOutputFilterByType SUBSTITUTE text/html
    SubstituteMaxLineLength 10m
    Substitute "s/foo/bar/ni"
</Location>