How to redirect abc.com/blog to blog.abc.com?

1. Caddy version (caddy version):

v2.5.1 h1:bAWwslD1jNeCzDa+jDCNwb8M3UJ2tPa8UZFFzPVmGKs=

2. How I run Caddy:

caddy reload
with Caddyfile

a. System environment:

Linux 5.4.0-109-generic #123-Ubuntu x86_64

b. Command:

caddy reload

c. Service/unit/compose file:

-

d. My complete Caddyfile or JSON config:

abc.com/blog {
	redir https://blog.abc.com{uri}
}

blog.abc.com {
	# Enable the static file server.
	file_server {
		root /home/user/blog
	}
}

3. The problem I’m having:

I successfully redirect www to non-www. Now I’m trying to redirect path to a subdomain, e.g.: abc.com/blog/something123 to blog.abc.com/something123
With above Caddyfile I get the following error and the redirect still not work.

4. Error messages and/or full log output:

WARN	caddyfile	Using a path in a site address is deprecated; please use the 'handle' directive instead	{"address": "http://abc.com/blog"}

5. What I already tried:

change the Caddyfile to:

handle /blog/* {
	redir https://blog.abc.com{uri}
}

blog.abc.com {
	# Enable the static file server.
	file_server {
		root /home/user/blog
	}
}

6. Links to relevant resources:

Please upgrade to v2.5.2

Do it like this:

abc.com {
	redir /blog* https://blog.abc.com{uri}
}

As the warning you got in your logs say, path matchers in the site address is deprecated, so you must put your path matcher within the site, applied to some directive.

What you tried with handle does not work because handle is a directive, it must go within a site block. Caddy will be parsing this as if handle is one of your domain names you’re trying to serve, but that doesn’t make sense. See the docs for the Caddyfile config structure:

Finally, I strongly suggest moving your site’s files to /var/www/html or /srv instead of having it in /home. You can run into permission issues by having it in /home if the user Caddy runs as can’t read those files.

blog.abc.com {
	root * /srv
	file_server
}
1 Like

Hi, thank you for your help.

I tried this:

When I access https://abc.com/blog/something it redirect to https://blog.abc.com/blog/something.
It still has /blog in it. Can we remove it?

Yeah, you can change it to this:

abc.com {
	handle_path /blog* {
		redir https://blog.abc.com{uri}
	}
}

The handle_path directive will strip the matched path segment before handling things within.

Keep in mind that requests that aren’t to /blog* will result in an empty response. You should probably configure something else to run for other paths.

1 Like

Thank you it works! :slight_smile:

I setup reverse proxy to handle other requests.

1 Like