Hosting an Tor website on NixOS
A few days ago, I setup a tor onion site on my little homelab for my website as an alternative to people using the clearnet version of this site. These are just some instructions that I wrote for it below:
Setting up Tor
To setup Tor, you will need to install on your server. Since I am using NixOS, I just used the following configuration (read the comments for more information):
1 services.tor = {
2 enable = true;
3 enableGeoIP = false; # I don't need to have access to the geolocation of IPs
4 relay.onionServices = {
5 # Any name is applictable here
6 "archvisions.org" = {
7 version = 3; # Version 3 of the onion url is more secure than version 2
8 map = [{
9 port = 80; # Port that Tor will serve onion site on. Keep on port 80 if you don't want a port number with the site.
10 target = {
11 addr = "127.0.0.1";
12 port = 80; # This is the port number that will be proxied through Tor. I pointed this to my reverse proxy Caddy.
13 };
14 }];
15 };
16 };
17
18 # Basic settings to configure Tor. I am not sure why these specifically, but they work.
19 settings = {
20 ClientUseIPv4 = false;
21 ClientUseIPv6 = true;
22 ClientPreferIPv6ORPort = true;
23 };
24 };
In relation to the relay.onionServices, you can pretty much put any name you want, but I just put my website domain. The settings inside of the map function matter more though, as that is basically the root of what you need to be hosting the onion site.
Setting up a reverse proxy
I use Caddy for my reverse proxy since it is easy to use (much easier than NGINX), but any reverse proxy will do.
Once you get Tor running (after a nixos-rebuild switch), you will need to get the onion site hostname. This can be found in the respective path at /var/lib/tor/onion/<name-of-onion>/hostname. Cat the hostname and paste it into your reverse proxy configuration.
Be sure to backup the private key in the directory of the onion site, else you will lose the onion site domain
For Caddy, my configuration is something like this:
1 services.caddy.virtualHosts."http://lsbh6bb7prcjxxl5fclu7tdz6mpywvcav5xamrevvunttez5fogfjtid.onion" = {
2 extraConfig = ''
3 encode gzip
4 root * /var/www/archvisions.org
5 file_server
6 '';
7 };This just simply takes the onion site url, and serves the static files of my website to Tor. Tor will look at that and proxy it over the Tor network with the specified onion address. Note that in Caddy, the onion site needs to have an "http://" before it as without it, Caddy will try to automatically grab a HTTPs certificate from LetsEncrypt.
Advertising the onion site
Tor supports advertising of the onion site on the clearweb site using the Onion-Location HTTP header. When you add the header, a button on the Tor browser appears:

In Caddy, this can be advertised using the header option:
header Onion-Location http://lsbh6bb7prcjxxl5fclu7tdz6mpywvcav5xamrevvunttez5fogfjtid.onion{path}