Help needed in converting Nginx rewrite to Caddy

I am trying to convert from Nginx to caddy, I have most of it but I am getting stuck on the rewrite.

rewrite "^(.*)/_images/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{28}).*$" /$1/images/$2/$2$3$4 break; rewrite "^(.*)/_thumbs/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{28}).*$" /$1/thumbs/$2/$2$3$4 break; rewrite "^(.*)/(.*)\.(php|css|js|gif|png|jpg|ico|html|manifest|appcache|txt|jar)$" /$1/$2.$3 break; rewrite "^(.*)/(.*)\?(.*)$ /$1/index.php?q=$2&$3" last; rewrite "^(.*)/(.*)$ /$1/index.php?q=$2" last; rewrite ^/(.*)$ /index.php?q=$1 last;

This is for Shimmie2.

Thanks.

That’s a lot of rewriting to do!

The general conversion of syntax when regex is involved is:

# nginx
rewrite $REGEX $DESTINATION $OTHER_STUFF;
# caddy
rewrite {
  r $REGEX
  to $DESTINATION
}

Where $1, $2, $3 etc. in nginx become {1}, {2}, {3} in Caddy.

https://caddyserver.com/docs/rewrite

2 Likes

That helps a lot thanks.

Now really quick about this line

rewrite “^(.)/_images/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{28}).$” /$1/images/$2/$2$3$4 break;

what happens with .*$" on the end of the regex?
or even a bunch of the $ I see around on the ends of lines

$ is what’s called an anchor; specifically, the end anchor. It signifies the end of line. ^ is the beginning anchor (start of line).

.* means zero or more of any character.

In the context of web requests, they are effectively meaningless and cancel each other out - you could remove any instance of .*$ from your Caddyfile with no effect. In a multiline regex, this structure would match a line of any length, but only one line.

A really good reference and testing tool for regex can be found here: http://www.regexr.com/

2 Likes

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