Nginx sub_filter 来修改html响应内容
首先,我们需要确保Nginx已经正确编译和安装,并且已启用了http_sub_module
和http_ssl_module
模块。您可以按照以下步骤进行操作:
-
下载和解压Nginx源代码,并进入解压后的目录。
wget https://nginx.org/download/nginx-1.23.0.tar.gz
-
执行以下命令来编译和安装Nginx:
./configure --prefix=/user/local/nginx --with-http_sub_module --with-http_ssl_module make sudo make install
这将编译并安装Nginx,并启用了
http_sub_module
和http_ssl_module
。 -
安装完成后,您可以执行以下命令来验证Nginx是否正确启用了
http_sub_module
:/user/local/nginx/sbin/nginx -V
在输出中,您应该能够看到
--with-http_sub_module
的信息。
接下来,我们将修改Nginx的配置文件,以在HTML响应中添加自定义的JavaScript代码。请按照以下步骤进行操作:
-
打开Nginx的配置文件。默认情况下,该文件位于
/user/local/nginx/conf/nginx.conf
-
在适当的位置,添加以下配置块:
server { listen 9999; location / { sub_filter '</body>' '<script>console.log("hello from Judith")</script></body>'; sub_filter_once off; root html; index index.html; } }
这将在所有请求的路径下应用
sub_filter
指令,并将</body>
替换为<script>console.log("hello from Judith")</script></body>
。请注意,
listen
指令可以根据您的需求进行修改,以适应您的实际情况。 -
保存并关闭Nginx的配置文件。
-
检查配置文件是否有语法错误:
/user/local/nginx/sbin/nginx -t
如果没有错误,将显示配置文件语法正确的消息。
-
重新启动Nginx以使更改生效:
sudo /user/local/nginx/sbin/nginx -s reload
或者
sudo systemctl reload nginx
-
在浏览器访问 如下图,可以看到这段js代码已经被加到 html 中
查看 index.html 源文件内容,如下图可以看出 index.html 源文件中并没有 console.log("hello from Judith")
这段代码
现在,当客户端访问Nginx提供的HTML页面时,Nginx将使用sub_filter
指令将</body>
替换为<script>console.log("hello from Judith")</script></body>
,从而在HTML中添加了一段自定义的JavaScript代码。
通过这种方式,我们可以方便地使用Nginx的sub_filter
模块来修改HTML响应,并根据需求添加自定义的JavaScript代码。
希望这篇博客对您有所帮助!如果您有任何其他问题,请随时提问。