2016-04-17

Redirect all your subdomains to a single https domain with nginx

On my playground server, I run a bunch of services in docker containers.
Most of them uses HTTP but don't natively support HTTPS so I'm using nginx as a front web server / reverse proxy to secure the connection.

I like to access my services using the following notation:

  • service1.example.com
  • service2.example.com

In fact, they all point to the same host and I'm using the DNS A records @ and *

The thing is, if I want to enable HTTPS for all these subdomains, I need as many legit SSL certificates. Another option is to buy a wildcard certificate but it's rather expensive ... for a playground server.

So I wrote this handy nginx config which permanently redirect HTTP requests to one unique HTTPS host:

  • http://service1.example.com => https://example.com/service1/
  • http://service2.example.com/path => https://example.com/service2/path

It also supports

  • http://example.com => https://example.com//


Ideally I'd get rid of the double trailing slash, but it'll work for now. Let me know if you have suggestions, this could certainly be enhanced


server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    # Match domain.tld or prefix.domain.tld
    server_name ~^(?<domain>[a-z0-9]*\.[a-z0-9]*)$ ~^(?<prefix>[a-z0-9]*)\.(?<domain>[a-z0-9]*\..*)$;

    error_log stderr;

    location / {
        rewrite ^ https://$domain/$prefix$uri permanent;
    }
}

No comments:

Post a Comment

Popular posts