Change filename extension on redirect

1. Caddy version (caddy version):

v2.3.0 h1:fnrqJLa3G5vfxcxmOH/+kJOcunPLhSBnjgIvjXV/QTA=

2. How I run Caddy:

caddy run

a. System environment:

Debian GNU/Linux 10

b. Command:

caddy run

c. Service/unit/compose file:

d. My complete Caddyfile or JSON config:


domain.com {
  reverse_proxy 10.10.10.101 {
        header_up X-Forwarded-Proto https
        header_up X-Forwarded-Port 443
        }

3. The problem I’m having:

I would like to implement a redirect that change both the location and case of the extension for all files ending with:

    https://domain.com/oldmedia/filename.JPG
    https://domain.com/oldmedia/filename.JPEG
    https://domain.com/oldmedia/filename.PNG
    https://domain.com/oldmedia/filename.GIF
    https://domain.com/oldmedia/filename.MOV
    https://domain.com/oldmedia/filename.AVI
    https://domain.com/oldmedia/filename.MPG

So they would be lowercase:

    https://domain.com/newmedia/filename.jpg
    https://domain.com/newmedia/filename.jpeg
    https://domain.com/newmedia/filename.png
    https://domain.com/newmedia/filename.gif
    https://domain.com/newmedia/filename.mov
    https://domain.com/newmedia/filename.avi
    https://domain.com/newmedia/filename.mpg

4. Error messages and/or full log output:

5. What I already tried:

Searched all documentation but still am not sure how to accomplish this.

Would this be possible with something like

redir https://domain.com/oldmedia/*.JPG https://domain.com/newmedia/{uri}.jpg

But then I would end up at

https://domain.com/newmedia/filename.JPG.jpg

6. Links to relevant resources:

You’ll probably need the path_regexp matcher for this, (or more simply with the map directive, but you’ll need a change coming in v2.4.0 to use map effectively here)

@jpg path_regexp jpg (.*)\.JPG
redir @jpg {re.jpg.1}.jpg

You’ll need to repeat this for each extension.

Thanks @francislavoie that does work perfectly fine.

If you want a bit of magic to reduce the number of lines in your config you could use import snippets to parameterize it. At the top of your config (after any global options):

(to-lower) {
	@{args.1} path_regexp {args.1} (.*)\.{args.0}
	redir @{args.1} {re.{args.1}.1}.{args.1}
}

Then in your site:

import to-lower JPG jpg
import to-lower JPEG jpeg
import to-lower PNG png
...
3 Likes

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