Nginx: Redirect Conditional on Server Name and Sub Domain for Short URLs

1.4k views Asked by At

I want to redirect conditionally based on the server name, but where I redirect to also depends on the subdomain. So for example, here is my basic config

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443;
    server_name company.com compa.ny;
    ssl on;
    ssl_client_certificate /etc/ssl/certs/godaddy_CA.crt;
    ssl_certificate /etc/ssl/certs/wildcard.company.com.crt;
    ssl_certificate_key /etc/ssl/private/wildcard.company.com.key;
    ssl_prefer_server_ciphers on;
    root /var/www/company;
    access_log /var/log/nginx/nginx.access.log;
    error_log /var/log/nginx/nginx.error.log;
    client_max_body_size 8M;
    location ^~ /application {
        proxy_set_header HOST $http_host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://127.0.0.1:8080;
    }
}

I want to have something that looks for the short url host "compa.ny" and redirects to "company.com/shortUrldRedirector" and I also want to include the subdomain, so in dev or qa this will work correctly:

https://compa.ny/abc123 -> https://company.com/shortUrldRedirector/abc123

and

https://dev.compa.ny/abc123 -> https://dev.company.com/shortUrldRedirector/abc123

I see there is a $server_name config variable, but how do I accomplish the above redirects respecting the subdomain?

1

There are 1 answers

4
ig0r On

I would use map construction like this:

map $http_host $long_domain {
    default      company.com;
    dev.compa.ny dev.company.com;
    compa.ny     company.com;
}

server {
    ...
    return 301 https://$long_domain/shortUrldRedirector$request_uri;
}