Is it possible mimic lookaheads and lookbehinds in redir and regex?

I’m trying to redirect any requests where the path does not start with /server/ followed by a major + minor version number, e.g., /server/10.2/, but not having much success. I’ve attempted to use the following rewrite block.

rewrite {
    r ^/server/(?![\d]{2}\.[\d]{1})(.*)
    to /server/10.2{1}
}

However, requests fails with error parsing regexp: invalid or unsupported Perl syntax: (?!`. From reading through the Caddy Server rewrite source, I see that it’s using regexp, which doesn’t support negative or positive lookbehinds and lookaheads.

Is there any other way to achieve the same affect?

Hi @settermjd, welcome to the Caddy community.

Well, rewrite also supports if subdirectives. Logically, the set of if conditionals, an ext conditional if given, and regex expressions must ALL match for a rewrite to execute.

I have to admit I’m a little confused as to what you want to achieve. I think you require it to start with /server, but only if it doesn’t have the versioning after it.

# Use path scoped rewrite to avoid running
# multiple regexes on every single request
rewrite /server {
  # Don't match '/server/10.2'-alike versioning
  if {path} not_matches ^/server/\d{2}\.\d{1}

  # Insert 10.2 element
  r ^/server{.*}$
  to /server/10.2{1}
}

https://caddyserver.com/docs/rewrite

@Whitestrake, sorry if I wasn’t as clear as I intended to be when describing my situation. From reading through the code sample that you provided, I believe that it should be the correct solution to my problem. Thanks for your feedback.

1 Like

No worries! Let us know if you’re still having any trouble after giving it a shot.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.