Implementing ~user home directories

I did not find a simple snippet to implement apache style ~username home directories. I know that with apache a user could be given rights to customize their home directory, but that is not possible with caddy. But the following Caddyfile snippet achieves a non-customized version of this:

	@user_home path_regexp user ^/~([^/]+)(/.*)?$
	handle @user_home {
		redir /~{re.user.1} /~{re.user.1}/ permanent

		root * /home/{re.user.1}/public_html
		rewrite * {re.user.2}
		file_server browse {
			hide .[A-Za-z]*
		}
	}
1 Like

Thanks for sharing this example!

What do you mean by this exactly, “given rights to customize their home directory”?

I made some adjustments to the config to simplify it.

I don’t think the redirect would have worked as-is, I don’t think vars_regexp works with placeholders, you need to give it an actual variable set with the vars directive. But it can be easily done with a path matcher to check if the path is bare.

1 Like

You can enable that users have their own snippets of config files, for example to be able to protect subdirectories with their own basic auth or to modify rules for directory listings and hidden files. This was out of scope for my simple try ro emulate home dirs with caddy.

I had to use that redirect in case a user has an index.html file referencing other files with relative paths, these would have the wrong directory otherwise. I tested it with an without the redirect, without relative path names in HREF or SRC tags won’t work.

Yeah, I understand why you have the redirect, but I just don’t think it was done correctly, is all.

Thanks, I tested this simpler form and it works fine.

2 Likes

I think that the uri strip_prefix is wrong, I changed it to:

rewrite * {re.user.2}

The reason is that the strip_prefix does not handle the case of an incoming uri being unescaped, for example it would not match www.example.com/~user/index.html. With the internal rewrite this works as well.

1 Like

Ups, the forum did change %7e to ~ in my example url.