Search code examples
nginxsubdomain

Nginx use subdomain as query parameter and rewrite URL


I'm trying to use subdomains as query parameter on the domain itself. An example would be the following:

I want nginx to take ab.example.com and call example.com?key=ab, now the backend will return a specific config, which should be used for the subdomain "ab".

Afterwards the user should see the content (logo branding to be precise) of example.com?key=ab but in the client's URL field the ab.example.com should persist.

And all further requests should show for example ab.example.com/login instead of example.com/login.

I hope that what I have said is sufficiently understandable. I have tried various examples from the internet and tried to find some hints.

The nginx file looks like:

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

    server_name www.example.com *.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com *.example.com;
    ssl_certificate /path/to/certs/ssl.crt;
    ssl_certificate_key /path/to/keys/ssl.key;

    root /var/www/example_site;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    location / {
        try_files $uri $uri/ /index.html =404;
        error_page 404 =200;
    }
}

I have already tried to map, but it redirects to a wrong domain:

map $host $subdomain {
    ~^(?<sub>.+)\.example\.com$ $sub;
}

And tried adding a static if statement in the server block, too:

if ($host = "ab.example.com") {
    rewrite . ?key=ab;
}

An additional server block did not help either:

server {
    listen 80;
    listen [::]:80;
    server_name www.ab.example.come ab.example.com;
    rewrite ^ https://example.com/?key=ab permanent;
}

Does anyone see what I am doing wrong or what part of the documentation I should read again?


Solution

  • You just need to do it inside your own server_name directive. You can assign a variable in a regexp directly there. If you need a different behavior for www. subdomain just remove *.example.com from the block and add this one in another file:

    server {
        listen       80;
        server_name  ~^(?<subdomain>.+)\.example\.com$; 
        return       301 http://example.com$request_uri?key=$subdomain;
    }
    

    Note that I didn't use rewrite, which you shouldn't need. Using return performs better. 301 stands for the kind of redirect. And then, you use your server_name assigned variable to redirect where you need.