Redirecting webfinger requests with Apache

If you have a personal domain, it is nice if you can redirect webfinger requests so you can be easily found via your email. This is hardly a new idea, but the growth of Mastodon recently has made this more prominent.

I wanted to redirect webfinger endpoints to a Mastondon host I am using, but only my email and only standard Apache rewrites. Below, replace xxx@yyy\.com with your email and zzz.social with the account to be redirected to. There are a couple of tricks in being able to inspect the query-string and quoting, but the end result that works for me is

RewriteEngine On
RewriteMap lc int:tolower
RewriteMap unescape int:unescape

RewriteCond %{REQUEST_URI} ^/\.well-known/webfinger$
RewriteCond ${lc:${unescape:%{QUERY_STRING}}} (?:^|&)resource=acct:xxx@yyy\.com(?:$|&)
RewriteRule ^(.*)$ https://zzz.social/.well-known/webfinger?resource=acct:xxx@zzz.social [L,R=302]

RewriteCond %{REQUEST_URI} ^/\.well-known/host-meta$
RewriteCond ${lc:${unescape:%{QUERY_STRING}}} (?:^|&)resource=acct:xxx@yyy\.com(?:$|&)
RewriteRule ^(.*)$ https://zzz.social/.well-known/host-meta?resource=acct:xxx@zzz.social [L,R=302]

RewriteCond %{REQUEST_URI} ^/\.well-known/nodeinfo$
RewriteCond ${lc:${unescape:%{QUERY_STRING}}} (?:^|&)resource=acct:xxx@yyy\.org(?:$|&)
RewriteRule ^(.*)$ https://zzz.social/.well-known/nodeinfo?resource=acct:xxx@zzz.social [L,R=302]

c.f. https://blog.bofh.it/debian/id_464