如何通过Nginx注入自定义内容?

pas*_*una 27 nginx code-injection

有没有办法为每个服务的php/html/etc注入几行脚本等.页?例如一些自定义的javascript在-tag之后?

我知道,你应该能够在nginx中使用lua但是有更好的解决方案吗?

我在nginx后面运行多个不同的Web应用程序,所以感觉这是正确的方法.我没有每个应用程序的访问源代码,维护这些代码会很麻烦.

pas*_*una 37

我找到了这样做的方法:http://nginx.org/en/docs/http/ngx_http_sub_module.html

location / {
    sub_filter </head>
        '</head><script language="javascript" src="$script"></script>';
    sub_filter_once on;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果内容是*gzipped*,则替换将不起作用.为此,添加`proxy_set_header Accept-Encoding"";`,它告诉后端在响应中不允许压缩. (8认同)
  • 请注意,默认情况下不会构建此模块(如链接文章所述),因此您的安装可能没有.你可以看看它是否有:`nginx -V`"将列出所有已配置的模块"([Source](http://serverfault.com/a/223526/138913))并寻找`--with -http_sub_module`. (2认同)