Apache – Troubleshooting LocationMatch Regex Behavior

apache-2.4regex

I am using the LocationMatch directive to set headers upon matching of certain URL patterns:

# 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>

However, the URL //mysite.com/ matches #1 instead of #2. Is this a bug or am I doing something wrong?

I even tried using the regex "^/(main|about)?$" in #2, but still no love.

Best Answer

It is possible to workaround it by using this configuration:

<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>

This way, the following requests work as expected:

# 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