Redirecting to non-http-based protocols with nginx

4 September 2021

I've written before about Gemini, a relatively young protocol for sending, receiving and interpreting text based files over the Internet. A cross between Gopher and HTTP.

Because Gemini — like HTTP — is built on top of other Internet technologies, it uses the Domain Name system. A side effect of this is that if you have a gemini capsule at gemini:// and somebody tries to load they will end up at whatever the default web site is on your server.

For my gemini capsule I dealt with this by just creating a landing page for the same domain name in the http/https world. But today I was looking into whether it's possible to simply redirect a whole site to the gemini protocol, and it turns out this is actually quite straightforward. The trick is to remember that http and https are themselves different protocols, yet we redirect from http to https all the time. In that case, it's easy to miss because they open the same files in the same browser. But if you have a Gemini browser like Lagrange, a redirect will open the URL in that application. If you're running nginx as your web server software, a redirect is as simple as making a block like this in your default site config, or as a separate file, in your sites-available directory:

server {
  listen 80;
  return 301 gemini://$host$request_uri;

To redirect both http and https, use certbot, which will essentially hoist your gemini redirect into an https block, and redirect http traffic to that (http => https => gemini). This will avoid users getting certificate errors, even though it feels like a waste of time given your https site is just redirecting to gemini.