![Apache LocationMatch 正则表达式行为似乎不正确](https://linux22.com/image/631775/Apache%20LocationMatch%20%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E8%A1%8C%E4%B8%BA%E4%BC%BC%E4%B9%8E%E4%B8%8D%E6%AD%A3%E7%A1%AE.png)
我正在使用LocationMatch
指令来在匹配某些 URL 模式时设置标头:
# 1
# Expected matches: //mysite.com/any-page-with-at-least-a-character-and-no-dot
<LocationMatch "^/[^\.]+$">
Header set X-Intelligence "STUPID"
</LocationMatch>
# 2
# Expected matches: //mysite.com/ , //mysite.com/main , //mysite.com/about
<LocationMatch "^/(|main|about)$">
Header set X-Intelligence "CLEVER"
</LocationMatch>
但是,URL //mysite.com/ 匹配的是 #1,而不是 #2。这是错误还是我做错了?
我甚至尝试使用"^/(main|about)?$"
#2中的正则表达式,但仍然没有效果。
答案1
可以使用以下配置来解决此问题:
<VirtualHost 127.0.0.1:80>
ServerName localhost
<Location "/">
Header set X-Intelligence "CLEVER"
</Location>
<LocationMatch "^/[^\.]+$">
Header set X-Intelligence "STUPID"
</LocationMatch>
<LocationMatch "^/(main|about)$">
Header set X-Intelligence "CLEVER"
</LocationMatch>
</VirtualHost>
这样,以下请求就可以按预期工作:
# curl -I -L http://127.0.0.1/ 2> /dev/null | grep X-I
X-Intelligence: CLEVER
# curl -I -L http://127.0.0.1/foo 2> /dev/null | grep X-I
X-Intelligence: STUPID
# curl -I -L http://127.0.0.1/about 2> /dev/null | grep X-I
X-Intelligence: CLEVER