如何实现nginx替换页面关键字?

Nginx

1 前言

一个问题,一篇文章,一出故事。
笔者生产环境反向代理代理一个应用,检查发现应用喜欢在页面自动写入结对路径,导致页面乱码。
详细的范例,

<link href="http://cmdschool.org/o/classic-theme/css/main.css" />

然后笔者希望删除协议头和主机名,即修改如下,

<link href="/o/classic-theme/css/main.css" />

2 最佳实践

2.1 普通替换场景

2.1.1 加入替换代码

vim /etc/nginx/conf.d/www.cmdschool.org.conf

加入如下配置,

location / {
	#...
	sub_filter 'http://cmdschool.org' '';
	sub_filter_types *;
	sub_filter_once off;
}

需要注意的是,
– 参数“sub_filter”声明替换的字符串,范例是把“http://cmdschool.org”替换为空字符串
– 参数“sub_filter_types”声明替换的类型,范例是替换css或html
– 参数“sub_filter_once”声明是否一次性替换,范例是关闭一次性替换即使用全局替换

2.1.2 重载服务使配置生效

systemctl reload nginx

2.2 上游开启压缩的替换场景

2.2.1 加入替换代码

vim /etc/nginx/conf.d/www.cmdschool.org.conf

加入如下配置,

server {
    listen       8080;
    server_name  localhost;

    location / {
        #...
        gzip off;
        proxy_set_header       Accept-Encoding "";
	#...
    }
}
server {
    listen       80;
    #...
    location / {
	#...
	proxy_pass http://localhost:8080;
	sub_filter 'http://cmdschool.org' '';
	sub_filter_types *;
	sub_filter_once off;
	#...
    }
}

需要注意的是,
– 以上代码适用于由于上游服务器开启压缩导致的替换失败
– 端口8080的代理服务先执行解压操作
– 端口80代理接过端口解压后的HTML流再执行替换操作
– 参数“gzip off”用于关闭当前服务器的压缩
– 参数“Accept-Encoding”置空用于关闭上游服务器的压缩

2.2.2 重载服务使配置生效

systemctl reload nginx

参阅文档
===================
http://nginx.org/en/docs/http/ngx_http_sub_module.html

没有评论

发表回复

Nginx
如何解决https请求不安全http页被阻止问题?

1 前言 一个问题,一篇文章,一出故事。 笔者最近代理公司应用,发现https的页面有请求不安全的h …

Nginx
如何Nginx代理上游的子项目或文件夹?

1 前言 一个问题,一篇文章,一出故事。 笔者接到任务需要把Tomcat的其中一个应用号使用Ngin …

Nginx
如何安装部署RHEL 9 Nignx?

1 前言 一个问题,一篇文章,一出故事。 笔者需要基于RHEL 9部署Nginx环境,于是整理此文。 …