nginx里面的rewrite配置

哎,我需要静静,刚刚在去怎么优化dom层级,发现更新完代码,层级又蹭蹭蹭的往上涨,顿时没脾气了,还是把昨天的nginx配置总结下,增加点动力,昨天前天两天都在搞这个问题,也是搞的没脾气,网上查了很多资料

问题:线上的css和js都是经过压缩的,自动生成版本号,因为去除后端的重定向,所以需要抓去线上的单个文件代理到本地
回答:找了半天没有解决方案,可以正则匹配,但不知道nginx里面怎么去用这个正则,nginx不支持js里面的replace,所以不能正则这样匹配,转化思路,还是抓取index.html首文件,在首文件价格参数,有environment这个参数,后端重定向,没有这个参数,后端不进行重定向

语法:rewrite regex replacement [flag];

如果一个URI匹配指定的正则表达式regex,URI就按照replacement重写,该指令通过正则表达式的使用用来改变URI。可以同时存在一个或者多个指令,按顺序依次对URL进行匹配和处理

 

flag可以是如下参数

last:停止处理后续rewrite指令集,然后对当前重写的新URI在rewrite指令集上重新查找。
break:停止处理后续rewrite指令集,并不在重新查找,但是当前location内剩余非rewrite语句和location外的的非rewrite语句可以执行。
redirect:如果replacement不是以http:// 或https://开始,返回302临时重定向
permant:返回301永久重定向

 

 niginx的内容设置中必须注意的一些问题

    1.nginx在进行rewrite的正则表达式中只会将url中?前面的部分拿出来匹配

    2.匹配完成后,?后面的内容将自动追加到url中(包含?),如果不让后面的内容追加上去,请在最后加上?即可

    3.如果要活的?后面的内容则请使用$query_string

rewrite实例

参数实例1
将
https://xxx/dist/index.html?a=1&b=2&c=3
转化为
https://xxx/dist/index1.html

location这么写

location /index.html {
  rewrite ^/(.*) /index1.html? redirect;
}
参数实例2
将
https://xxx/dist/index.html?a=1&b=2&c=3
转化为
https://xxx/dist/index1.html?a=1&b=2&c=3&d=4

location这么写

location /index.html {
  rewrite ^/(.*) /index1.html?d=4&$query_string? redirect;
}
参数实例3
将
https://xxx/dist/index.html?a=1&b=2&c=3
转化为
https://xxx/dist/index.html?a=1&b=2&c=3&d=4

location这么写

set $flag 0;
if ($request_uri ~* "index.html") {
    set $flag "${flag}1";
}

if ($query_string !~* "^.*d=S*.*$") {
    set $flag "${flag}2";
}

if ($flag = "012") {
    rewrite ^/(.*) /index.html?d=4&$query_string? redirect;
}
location /dist/index1.xhtml { //后端重定向地址
    rewrite ^/(.*) /dist/index1.html redirect;
}
原文地址:https://www.cnblogs.com/wzndkj/p/7844649.html