Rewrite Rules from Apache to Caddy

I need help converting a site i have on apache to caddy. how would i write these directives in my Caddyfile?

RewriteCond %{REQUEST_URI} !^/index.php$
RewriteCond %{REQUEST_URI} "!^/resource/"
RewriteRule ^(.*)$ /index.php?url=$1 [NC,L]

Please fill out the help topic template, as per the forum rules.

1. Output of caddy version:

v2.5.1 h1:bAWwslD1jNeCzDa+jDCNwb8M3UJ2tPa8UZFFzPVmGKs=

2. How I run Caddy:

a. System environment:

Ubuntu Server 22.04, caddy from default apt repo

b. Command:

systemctl start caddy

c. Service/unit/compose file:

[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target

[Service]
Type=notify
User=caddy
Group=caddy
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target

d. My complete Caddy config:

beta.evertek.com {
	root * /var/www/Evertek
	file_server
	php_fastcgi * unix//run/php/php7.4-fpm.sock
        rewrite {
            to {path} /index.php?url={path}
        }
}

3. The problem I’m having:

I need help converting a site i have on apache to caddy. how would i write these directives in my Caddyfile?

RewriteCond %{REQUEST_URI} !^/index.php$
RewriteCond %{REQUEST_URI} "!^/resource/"
RewriteRule ^(.*)$ /index.php?url=$1 [NC,L]

4. Error messages and/or full log output:

no error messages, just redirecting still in /resource

5. What I already tried:

Ive tried using rewrite already in my config file, but i dont know the relevant config options to not rewrite if the url is in the /resource/ folder

6. Links to relevant resources:

1 Like

That’s not valid, that’s Caddy v1 syntax and isn’t supported in v2.

The way to do this in v2 is to adjust the try_files subdirective of php_fastcgi. See the docs for the directive, and read the explanation of the expanded form to understand how it works.

I don’t think the /resources condition matters though, unless you also have PHP files in that directory. Requests to files that do exist on disk will not be rewritten because of the {path} part.

FWIW, I recommend changing your PHP app to not use the query to read the original URI, but instead read from the REQUEST_URI server variable. That’s the standard/modern way of doing it. Rewriting to add something to the query is janky and not recommended.

1 Like

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