Negating matches in Apache locations
It took me some time to figure it out so why not sharing it with the world?
Apache allows you to add basic auth to parts of your site using the Location directive. When restricting access to all resources you might add a section like this to your VirtualHost:
<Location /> AuthUserFile /path/to/.htpasswd AuthName "geschuetzter Bereich" AuthType Basic require valid-user </Location>
/ means that any access to your server is restricted. Today I’ve been looking for a way to restrict all resources on the server but one. It’s not that easy using standard regular expression but as Apache uses Perl compatible regular expressions you can use lookahead assertions to negate an expressions:
<Location ~ "^/(?!path/that/doesnt/need/auth)"> AuthUserFile /path/to/.htpasswd AuthName "geschuetzter Bereich" AuthType Basic require valid-user </Location>
With ~ you are telling Apache that you are using an extended regular expression. ^ is the beginning of the line, ?! initializes a negated lookahead assertion. Any path that is not in the String given above will require authentication.
Big thank you to our administrators who’ve been kind enough to share a lot of their wisdom with me.