Nginx:为400状态代码显示除少数路径之外的所有路径的错误页面

时间:2017-06-20 12:02:35

标签: regex nginx nginx-location

我需要在url中进行模式匹配,这会排除某些文件,并在获取错误代码400时显示错误页面

例如:我有网址/test/v1//test/v2/。我需要为所有/test/x显示自定义错误页面(状态400),其中x可以是任何内容,/test/v1//test/v2/除外。

那么我在nginx.conf文件中的location指令中的正则表达式应该是什么,我在下面试过但是失败了。

location ~* /test(?!\/(v1|v2)) {
    proxy_intercept_errors on;
}

error_page  400 /400.html;

2 个答案:

答案 0 :(得分:0)

这是一个建议:

\/test\/(v1|v2)\/?

它允许/test/v1//test/v2/(没有最终斜杠也可以) 它在/test/nope//nope时失败。

Test it on regex101

答案 1 :(得分:0)

Allow test/(v1|v2)/, and disable all the rest:

location ~* /test(\/(v1|v2)\/) {
    try_files $uri $uri/ =404;
    break;
}


location / {
     return 400 "bad request";
}