regexapache.htaccesshttpd.conf

Proper Syntax for RegEx in Apache Directive Containers


  1. What is the proper syntax to use RegEx with <Directory> and <DirectoryMatch> container paths? I'm just confused about the usage of ~ and ^. When and how should they be used?
<Directory ~ /home/user/(site|sitedev)>
    ...
</Directory>
<DirectoryMatch ^/home/user/(site|sitedev)>
    ...
</DirectoryMatch>
  1. Are quotes always required or only when there's a space or special character in the value?
"/home/user/(site|sitedev)"
/home/user/(site|sitedev)
  1. Also, what would be a RegEx to match all of the following folders:
/home/my/site
/home/my/siteblog
/home/my/sitestore
or any other that starts with /home/my/site doesn't go deeper like /home/my/siteblog/random

Can these two be a solution and what is the difference?

^/home/my/site.*
/home/my/^site.*

Solution

  • I'm not a specialist but I would say:

    1. <Directory ~ "^/home/user/(site|sitedev)">
      is equivalent to
      <DirectoryMatch "^/home/user/(site|sitedev)">
      Both are core built-in. I prefer the second one as it's much clearer to read for a beginner.

    2. You are right, quotes are required in case of spaces.
      I personally always quote them, for consistency in the config file.

    3. ^/home/my/site.* is the correct one:

      • ^ means "beginning with". This is why it can't be put before "sites" like you mentioned in /home/my/^site.*. If you don't put this ^ at the beginning, then an URL such as /test/home/user/sitedev would also match. This is because a pattern is used like a search and if it's found in the path then it matches, and you'll enter the <DirectoryMatch> block.

    In opposite of ^, you can use $, meaning "finishing with".
    This is useful to match all JPEG files with \.jpe?g$, where the dot should be escaped because . means "any character" and ? means that the "e" char before is optional. Of course, this example would not be used on a <DirectoryMatch> but on a <FilesMatch>.

    Caution, the regex can be case-sensitive or not, so it could not match /img/IMG234.JPG depending on the config. I think this depends on RegexDefaultOptions. If ICASE is "on" or not.

    But I usually prefer solving this config question by enabling the "case-insensitive" flag at the beginning of the pattern with (?i)\.jpe?g$ or enabling it for a specific part by wrapping it between (?i: and ) like this: (?i:\.jpe?g)$.

    Examples: