How to elegantly (wildcard) redirect from non-www and www to a specific subdomain, eg. `main` or `app`

74 views Asked by At

I am not sure, if I built myself a terrible foot-gun of some sort here with my approach of redirecting any traffic from non-www/www to a subdomain (say main), which is the landing page of the service.

Why I don't have the landing page and subsequent links on the plain domain is another (and valid) question, and for now, I would prefer to keep the database schemas like this. I use django-tenants and keep the public schema empty. The subdomain to which traffic is redirected, should remain the main entry-point to all subsequent services/tenants.

I browsed through plenty of nginx docs for weeks now, deferred the issue again and again and as of now cannot think of anything other than this very inelegant, but working (for now) solution:

server {
    listen 80;
    listen [::]:80;

    server_name .example.com;

    location / {
        return 301 https://$host$request_uri;
    }
}

server {

    listen 443 ssl;
    listen [::]:443 ssl http2;

    server_name example.com www.example.com;

    location / {
        return 301 https://main.example.com$request_uri;
    }
}


server {
    listen 443 ssl;
    listen [::]:443 ssl http2;

    server_name main.example.com sub1.example.com sub2.example.com sub3.example.com;

    location / {
        root   /usr/share/nginx/html;
        index  index.html;
        try_files $uri $uri/ /index.html;
    }
}

This works for now, but the service is going to have N subdomains/tenants in the future, so line

server_name main.example.com sub1.example.com sub2.example.com sub3.example.com;

will eventually be preferable like

server_name .example.com;

I tried with e.g.

server_name main.example.com .example.com;

but this yields a cyclic behavior, resolving the address to always main.example.com.

I am thinking of constraining the subdomains to a regex-able pattern, on the other hand, there has to be something cleaner.

I am out of good ideas on this one and appreciate any feedback on how to untie this.

0

There are 0 answers