How this site does userdirs in nginx

(update: as of april 2023 this is out of date, see my co-admin's post about how she changed this)

If you can't tell, this site has user dir pages (that is, /~elle/notebook.html reads from the file /home/elle/public_html/notebook.html). I've spent a while tweaking the nginx server config for this, and I think I'm reasonably happy with the results:

(if you just want to steal the code, it's at the bottom)

location ~ ^/~(.+?)(/.*)?$ {

this matches against the location /~(thing)(optional path)

root /;

this sets the filepath root to / instead of your nginx server dir

try_files /home/$1/public_html$2 /home/$1/public_html$2.html @redirect; }

this tries in order, the path in the url as given, and then (path).html, which lets you access pages without specifying the html extension. If neither of these match a file, it loads the @redirect location, which:

location @redirect { return 301 $request_uri/; }

redirects the user with a 301 (permanent redirect) to the url with a trailing slash, which will then match:

location ~ ^/~(.+?)(/.*)?/$ {

this location, which is used to handle directories.

root /;

this sets the filepath root to / instead of your nginx server dir

try_files /home/$1/public_html$2/index.html =404;

which then tries to load (directory)/index.html, then, failing that, returns a 404.

}

This does a few nice things:

The full code is given below. I give no guarantees this will work, do anything, not compromise your entire system, etc.

location @redirect {
	return 301 $request_uri/;
}

# automatically load index.html for directories accessed through dir/
location ~ ^/~(.+?)(/.*)?/$ {
	try_files /home/$1/public_html$2/index.html =404;
}

# load files, or redirect to dir/ if there's no specific file
location ~ ^/~(.+?)(/.*)?$ {
	try_files /home/$1/public_html$2 /home/$1/public_html$2.html @redirect;
}