Rewrite URI subdirectory into query string parameter

1. Output of caddy version:

v2.6.2 h1:wKoFIxpmOJLGl3QXoo6PNbYvGW4xLEgo32GPBEjWL8o=

2. How I run Caddy:


3. The problem I’m having:

I have searched for the last hour, but I’m completely stumped.

I want the URI to be rewritten internally to

I feel like the rewrite directive is what I want, but I cannot figure out how to get it to work.

In nginx I would use something like this:

rewrite "^/(.+)$" /index.php?file=$1 break;

4. Error messages and/or full log output:

Paste logs/commands/output here.

5. What I already tried:

From the rewrite examples, but I don’t know how to get “b” from the URI!

rewrite /* ?file=b

Alternatively I tried examples I found from ~2017 (which I think is Caddy v1??) which throw an error, e.g.

rewrite {
  r ^/(.+)$
  to /index.php?file={1}

Thanks for looking

You want to do this for all requests? Or only some? This matters.

You haven’t shared what the rest of your config looks like, so we’re missing some important context here.

You might need a solution using rewrite or a solution using try_files, but it depends on what you’re doing with the request.

But in general, it might look like rewrite * /index.php?file={path} if you need to rewrite all requests unconditionally.

@francislavoie thank you so much - that’s exactly what I needed and it works perfectly. I now see where I was going wrong, and it seems so obvious now :roll_eyes:

For reference, this is the working config for the site:

http://testsite.local {
  encode gzip

  root * /srv/testsite

  php_fastcgi php-fpm:9000 {
    index index.php

  rewrite * /index.php?file={path}

Thanks again,


Since you’re using php_fastcgi, then you’d probably want to do this instead:

http://testsite.local {
	root * /srv/testsite
	encode gzip
	php_fastcgi php-fpm:9000 {
		try_files {path} {path}/ /index.php?file={path}

Interesting… That doesn’t actually work for me, but that’s probably down to what I’m doing with the PHP script. The rewrite works perfectly for my use case.

This topic was automatically closed after 30 days. New replies are no longer allowed.