Nginx on nixos: Redirect www to non-www?

I have an entry like this:

    virtualHosts."mydomain.com" = {
      enableACME = true;
      forceSSL = true;
      locations."/" = {
        proxyPass = "http://127.0.0.1:8000";
        extraConfig = ''
          proxy_pass_request_headers on;
          proxy_set_header Cookie $http_cookie;
          proxy_set_header Host $host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header X-Real-IP $remote_addr;
        '';
      };
    };

And I’ve setup an A record for the www.mydomain.com subdomain. How can I create a redirect from www.mydomain.com to mydomain.com in nginx? I’ve tried to read https://github.com/NixOS/nixpkgs/blob/4353938ac7c3f91ad7dcefba16c51df392cf5555/nixos/modules/services/web-servers/nginx/default.nix, but I don’t understand enough of it.

You can create virtual host for www.mydomain.com and use the globalRedirect option. Do not forget to also set up the TLS certificate.

3 Likes

Thanks! I added this:

    virtualHosts."www.mydomain.com" = {
      enableACME = true;
      forceSSL = true;
      globalRedirect = "mydomain.com";
    };

And that worked :slight_smile:

1 Like

For bonus points, you can also replace enableACME = true with useACMEHost = "mydomain.com"; and add

security.acme.certs."example.com".extraDomainNames = [
  "www.example.com"
];

To reduce the number of certificates that need to be generated.

4 Likes