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
没有评论