regexgocaddycaddyfile

Regular expression negative lookaheads RE2 syntax used by Caddy


When translating my Apache and Nginx configuration to Caddyfile, I'm having a problem with a regular expression. I use the following in Apache to restrict access to files and directories that start with a dot (.) and are not in the .well-known directory.

<IfModule mod_authz_core.c>
    <LocationMatch "(^|/)\.(?!well-known/)">
        Require all denied
    </LocationMatch>
</IfModule>

This is an Apache configuration block that uses the mod_authz_core module to deny access to any files or directories that begin with a dot (.) in the requested URL path, except those in the .well-known directory:

@block {
    path_regexp ^(\/\..*)$
    not path_regexp "^/\.well-known\/.*$"
}
respond @block 403

However, I'd like to use a single regular expression without using not path_regexp.

The problem is the negative lookahead syntax in the regexp. The RE2 syntax used by Caddy does not support the (?!pattern) syntax for negative lookaheads.

Now I'm stuck, even after reading previous questions about this issue, I can't figure out how to solve this. Any ideas?

If you're curious, Nginx equivalent:

location ~* /\.(?!well-known\/) {
  deny all;
}

Solution

  • It’s not possible using a single regex if negative lookaround isn’t supported. This is not something that regexes do other than working around it using the negative lookaround syntax, so if that’s not supported then it’s not possible.