首页 > 解决方案 > Nginx - 位置指令中的参数数量无效 - 正则表达式捕获带有空格的组

问题描述

您好,我有一个位置指令,其中包含不区分大小写的正则表达式匹配,如下所示:

location ~* (/path/to/file withspace|/path/to/anotherfile) {
  return 404;
}

当我重新加载 nginx 时,我收到以下错误消息

nginx: [emerg] invalid number of arguments in "location" directive

经过一番故障排除后,我发现问题出在/path/to/file withspace.

然后我尝试了以下方法,它有效

location ~* "/path/to/file withspace" {
  return 404;
}

但我无法使用管道来处理要处理的路径,这对我来说很麻烦。

所以:

谢谢

标签: nginx

解决方案


nginx 在解析配置时会看到该空间,因此它将您的位置路径视为/path/to/file,但是当它期望 时{,它会看到其余的withspace

最简单的方法是在你的正则表达式中使用空白元字符,所以用它\s来表示任何空白:

location ~* /path/to/file\swithspace {
  return 404;
}

如果您想非常精确地了解空格字符而不是制表符等,请使用十六进制字符代码作为空格\x20

location ~* /path/to/file\x20withspace {
  return 404;
}

编辑:我忘记了一个更通用的功能,即 nginx 允许您在配置中的任何位置转义特定字符,只需使用\. 当您想要包含外来字符或避免识别保留字时,这很有用,但也应该可以解决这个问题:

location ~* /path/to/file\ withspace {
  return 404;
}

推荐阅读