Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get subdomain of URL in NGINX

I am wanting to do a redirect based on what subdomain the user is entering.

For example:

<subdomain>.example.com/admin -> <subdomain>.myurl.com

Ideally I want to pass <subdomain> as a parameter to my redirect URL.

I was looking at something along the lines of this:

location ~ (sub).(somewhere).(com)/(some)(thing)/(something)(else) {
  set $var1 = $1; # = sub in above example
  set $var2 = $2; # = somewhere in above example
  set $var3 = $3; # = com in above example
  set $var4 = $4; # = some in above example
  set $var5 = $5; # = thing in above example
  set $var6 = $6; # = something in above example
  set $var7 = $7; # = else in above example
  rewrite ^ $1/$2 last; # would be sub/somewhere
}

based on this post here: Manipulate or split string (I think the syntax of the variable set is wrong in this example but you get the gist).

like image 237
Stretch0 Avatar asked Sep 18 '16 21:09

Stretch0


1 Answers

The domain name part of the URL is not tested by the location directive. You will need to use a named capture in the server_name directive. See this document for details.

For example:

server {
    server_name ~^(?<name>\w+)\.example\.com$;

    location /admin {
        return 301 $scheme://$name.myurl.com/;
    }
}
like image 172
Richard Smith Avatar answered Oct 13 '22 13:10

Richard Smith