Rewrite if the requested file does not exist (conversion from nginx configuration)

Hello,

I’m testing Caddy as a replacement for nginx on my NAS (mainly due to easier syntax than nginx). I converted most of my existing configurations without issue. However, I’m not sure (I searched already) how to handle the nginx directive below:


 # All non existing files are redirected to index.php
 if (!-e $request_filename){
     rewrite ^/data/public/([a-zA-Z0-9_-]+)$ /public/$1?;
     rewrite ^(.*)$ /index.php last;

Looking at the docs, and searching around didn’t give me many clues on how the Caddy equivalent would be. Is this possible with the current version?

Hi @lbeltrame,

The rewrite directive takes multiple inputs to its to subdirective, and it will try each one in order before falling back to the last input if none of the others exist.

You can choose to fall back to index.php in each case, for both rewrites, which should get you the result you’re after.

In your case, with your regex taken into account, the rewrite blocks should look something like this untested example:

# This one catches /data/public/* and tries /public/*, followed by index.php
rewrite {
  r ^/data/public/([a-zA-Z0-9_-]+)$
  to /public/{1} /index.php
}
# This is a catch-all, tries for a file, then a dir, followed by index.php
rewrite {
  to {path} {path}/ /index.php
}

https://caddyserver.com/docs/rewrite

Thanks, will give it a try shortly.

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