Try_files Rewrite Request exclude path help plz

Hi, I need to enable rewrite rules on my WordPress site with Caddy 2 server.

When I was on NGINX, I was doing the following:

location / {
try_files $uri $uri/ /index.php$args;
}

In the same way when I just keep:

try_files {path} {path}/ /index.php?{query}

on Caddyfile, everything is working fine except I am getting error too many redirects on:

https://mysite.com/wp-admin/

path. So, it is necessary that I must exclude /wp-admin/ path from rewrite since rewrite for that path is not necessary for me.

That were the main problem appeared I tried many ways but I am unable to exclude /wp-admin/ path from try_files directive. I checked documentation many times but I don’t see a way to exclude a path.

I tried to validate with many ways but failed such as the following: So please help me!

@try_files {
file
not path /wp-admin/* {
try_files {path} {path}/ /index.php?{query}
}
}
rewrite @try_files {http.matchers.file.relative}

@wp-admin {
not path /wp-admin/*
}
rewrite @wp-admin {path} {path}/ /index.php?{query}

@wp-admin {
not path / /wp-admin/*
}
rewrite @wp-admin /index.php?{query}


@wp-admin {
not path /wp-admin/*
}
rewrite @wp-admin {path} {path}/ /index.php?{query}

@wp-admin {
not path /wp-admin/*
}
try_files @wp-admin {path} {path}/ /index.php?{query}

@try_files {
not path /wp-admin/*
try_files {path} {path}/ /index.php?{query}
}
rewrite @try_files {http.matchers.file.relative}

I think you were on the right path with your first attempt using the expanded form of try_files. the matcher looks a bit malformed however, please see https://caddyserver.com/docs/caddyfile/matchers#named-matchers.

Try this instead

@try_files {
    not path /wp-admin/*
    file {
        try_files {path} {path}/ /index.php
    }
}
rewrite @try_files {http.matchers.file.relative}

edit: removing ?{query} from code snippet as it is implied, thanks @francislavoie

2 Likes

The ?{query} bit is unnecessary, Caddy retains the query parameters when rewriting.

1 Like

@cupanoodle thank you man you are awesome! & @francislavoie thank you too!!

1 Like