Regular expression negative lookaheads RE2 syntax used by Caddy

huangapple go评论73阅读模式
英文:

Regular expression negative lookaheads RE2 syntax used by Caddy

问题

将Apache和Nginx配置翻译为Caddyfile时,我在正则表达式方面遇到了问题。在Apache中,我使用以下配置来限制访问以点(.)开头且不在.well-known目录中的文件和目录。

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

这是一个Apache配置块,使用mod_authz_core模块来拒绝访问请求URL路径中以点(.)开头的任何文件或目录,但.well-known目录除外。

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

然而,我想使用一个单独的正则表达式,而不使用not path_regexp

问题在于正则表达式中的负向先行断言语法。Caddy使用的RE2语法不支持(?!pattern)这种负向先行断言语法。

现在我陷入了困境,即使阅读了关于这个问题的先前问题,我也无法解决它。有什么想法吗?

如果你好奇,以下是Nginx的等效配置:

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

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.

&lt;IfModule mod_authz_core.c&gt;
    &lt;LocationMatch &quot;(^|/)\.(?!well-known/)&quot;&gt;
        Require all denied
    &lt;/LocationMatch&gt;
&lt;/IfModule&gt;

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 &quot;^/\.well-known\/.*$&quot;
}
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;
}

答案1

得分: 0

如果不支持负向环视,使用单个正则表达式是不可能的。除非使用负向环视语法绕过此问题,否则正则表达式无法完成此操作。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月17日 21:57:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定