Nginx – In Nginx, map specific subdomains to ports, redirect all others

nginxredirectsubdomainwildcard-subdomain

I'm trying to accomplish three things:

  1. Map traffic, by subdomain, to one of several applications on different ports.
  2. If subdomain isn't recognized, redirect to www.
  3. Require HTTPS on all subdomains.

My nginx configuration so far is:

map $subdomain $subdomain_port {
  default    8000;
  www        8000;
  subdomain1 8001;
  subdomain2 8002;
  subdomain3 8003;
}

server {
    listen 80;
    listen [::]:80;
    server_name _;
    return 301 https://$host$request_uri;
}

server {
    listen              443 ssl;
    server_name         ~^(?P<subdomain>.+?)\.mydomain\.com$;

    ssl_certificate     <cert>;
    ssl_certificate_key <key>;

    location / {
      # ... various proxy headers, then ...
      proxy_pass http://127.0.0.1:$subdomain_port;
      proxy_redirect off;
    }
}

This almost works (it accomplishes #1 and #3), but instead of redirecting foo.mydomain.com to www.mydomain.com, it just serves the www content without redirecting. I'm not sure how to redirect un-mapped subdomains without splitting the whole thing into separate server blocks, which I'd really rather not do.

Is there a way to redirect all subdomains not explicitly mentioned in the map to www?

Best Answer

Just implement a default server. Here's mine

server {
  listen      80 default_server;
  server_name _;
  return 302 https://www.example.com;
}

You can do whatever action you want.