'Using RegEx in Apache's directives in config files and .htaccess
If I understand correctly expression .ht* in the next code will match all that starts with .ht, so my .ht_lalala is safe.
<Files ".ht*">
Require all denied
</Files>
But what about next one?
(^\.ht|~$|back|BACK|backup|BACKUP$)
Is it correct for matching files: .htaccess, back, backup, BACKUP? Or next will be better instead
(^\.ht*|back*|BACK*$)
What I'd like to understand is what ~$ actually means in my code (in RegEx pattern). I don't know why and when I put it there, but I have it in my code, and now I doubt that it's correct.
I know basic things about RegEx, what is ^ and $, and that * means 0 or N from previous text/token, but ~ doesn't make sense inside the pattern, unless it's just a simple character and it does nothing but literally matches ~. I've read Apache docs, I guess for multiple matches FilesMatch and DirectoryMatch is better, however regular expressions can also be used on directives: Files and Directory, with the addition of the ~ character, as is stated in the docs examples.
<Files ~ "\.(gif|jpe?g|png)$">
#...
</Files>
And well, what I want exactly is to know how to match different files or directories.
One more thing, should I escape the .? Because default httpd.conf doesn't do so. Or it's just different for httpd.conf and .htaccess (which doesn't make sense to me)
UPDATE
Answering to my own question, how do I match with RegEx any of this .ht, .htaccess, .htpasswd, back, BACK, backup, BACKUP, first at all I decided to use . (dot) in the name of anything I want to hide. Secondly, I found out that laconic pattern ^(\..*)$ will do the job, will give me what I need. Or ^\. even better! So, if in the future I would like to hide something, I just add the . at the start of the name.
Here we go, next code will deny access from the web to any files and directories which names start with . (tested, works)
RegEx pattern match:
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<DirectoryMatch "^\.">
Require all denied
</DirectoryMatch>
And in brilliant explanation @MrWhite clarified and simplified my method, so I stuck with this (tested, works)
Wild-card string match:
<Files ".*">
Require all denied
</Files>
<Directory ".*">
Require all denied
</Directory>
Solution 1:[1]
The Apache manual covers this.
~ enables regex. Without it, you just get access to wildcards ? and *.
As far as I know Apache uses the PCRE flavor of regex.
So once you've enabled regex via ~ then use https://regex101.com/r/lPkMHK/1 to test the behavior of the regex you've written.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zoe stands with Ukraine |
