如何在Apache LocationMatch中编写匹配URL结尾的正则表达式?
Apache LocationMatch匹配后缀请求头不生效的解决方案
问题场景
需要匹配所有路径下以mobiles.touch.json结尾的请求,为这类请求单独设置请求头,但尝试三种配置均未生效:
- Option1:
<LocationMatch "/mobiles.touch.json"> - Option2:
<LocationMatch "/(mobiles.touch.json)"> - Option3:
<LocationMatch "/mobiles.touch.json$">
目标匹配的URL示例:
${domainname}/abc/abc/abc/jp/mobiles.touch.json${domainname}/xyz.net/ert/ert/ert/mobiles.touch.json${domainname}/abc/def/def/as/mobiles.touch.json
问题原因
- 前两种配置仅匹配包含
/mobiles.touch.json的请求,未限制结尾;同时未转义正则中的.(.在正则中表示任意字符,会误匹配类似mobilesxtouchxjson的路径) - 第三种配置仅匹配根目录下的
mobiles.touch.json(即URI为/mobiles.touch.json的请求),无法匹配带前置路径的目标URL
正确配置方案
使用转义后的正则,匹配任意前置路径+目标后缀的请求:
<LocationMatch "^.*/mobiles\.touch\.json$"> # 示例:设置自定义请求头 Header set X-Custom-Header "Your-Value-Here" </LocationMatch>
正则说明
^.*:匹配请求URI开头到最后一个/的任意内容(支持空路径,即根目录下的目标文件)/mobiles\.touch\.json$:严格匹配以/mobiles.touch.json结尾的URI,\.转义正则中的.,避免误匹配- 确保Apache已启用
headers模块:- Debian/Ubuntu系统执行:
a2enmod headers - RHEL/CentOS系统在
httpd.conf中添加:LoadModule headers_module modules/mod_headers.so
- Debian/Ubuntu系统执行:
验证方法
用curl发送请求检查响应头:
curl -I ${domainname}/abc/abc/abc/jp/mobiles.touch.json
查看输出是否包含你设置的自定义请求头。
内容的提问来源于stack exchange,提问作者ezhil
相关产品推荐
相关产品推荐

