简单的 nginx server_name 正则表达式找不到匹配项

简单的 nginx server_name 正则表达式找不到匹配项

我在 AWS 上有一个运行 1.8.1 版本的 nginx 盒子。我正在将许多 DNS 路由条件转换为 nginx,并且遇到了许多*.yet_another_domain.*有用的 DNS 条目,但 nginx 似乎不喜欢在主机的两侧都有通配符(文档中的“或”指的是通配符可以放在哪一侧,对软件开发人员来说可能是一个有偏见的词)。因此,我转向正则表达式。

我在本地主机上为 uno.com 和 www.uno.com 设置了主机条目,将它们指向我的 nginx 框。使用 server_name 值(例如www.uno.com uno.com或).uno.com可以得到结果,因此我知道当我不依赖正则表达式时,nginx 能够命中我的配置(*.uno.com这是另一回事,存在一些缺陷,但我离题了)。我尝试了许多正则表达式,但 nginx 都没有匹配 uno.com 或 www.uno.com。

我尝试过的一些正则表达式:

server_name ~^(.*\.?uno\..*)$;(希望匹配 www.uno.com 和 uno.com)

server_name ~^(.*\.)?uno\.com$;(还请查找 www.uno.com 和 uno.com)

server_name ~uno\.com;(只需在主机的任何地方寻找 uno.com)

server_name ~^uno.*;(寻找以 uno 开头的主机)

每当我使用任何这些正则表达式查找 uno.com 或 www.uno.com 时,我的 AWS nginx 实例都会返回一个漂亮的 nginx/Amazon 测试页面,但不会返回我正在寻找的硬编码返回值。

答案1

问题就在这里。我的 nginx.conf 中有一个包含目录的文件,而这个目录中有多个其他 .conf 文件。在其中一个文件中,有一个 *.com 的 server_name。根据 nginx 处理请求的规则,通配符 server_name 的优先级高于正则表达式 server_name。现在,这实际上是我意识到的事情——真正让我感到困惑的是,如果没有发现有效位置,nginx 显然不会回头寻找其他可能的 server_name 匹配项。真糟糕。

下面是对 nginx 请求解析过程的详细描述,它帮助我意识到它不会像我希望的那样去寻找其他 server_name 匹配项:

https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms

相关内容