unable to get subdomain of URL in NGINX

+4 votes

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

For example:

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

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
}

Mar 26, 2018 in DevOps on Cloud by Atul
• 10,240 points
594 views

2 answers to this question.

+2 votes

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

For example:

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

    location /admin {
        return 301 $scheme://$name.myurl.com/;
    }
}
answered Mar 26, 2018 by DareDev
• 6,810 points

edited Oct 11, 2018 by Kalgi
+2 votes

You just need to add .+ after ?< subdomain >:

server {
    listen  80;
    server_name     *.example.com;

    return 301 https://$http_host$request_uri$is_args$args;
}

server {
    listen 443 default_server ssl;

    server_name     ~^(?<subdomain>.+)\.example\.com$;

    ssl                     on;
    ssl_certificate         /etc/ssl/certs/example.com.crt;
    ssl_certificate_key     /etc/ssl/private/example.key;

    root    /var/www/example.com/apps/$subdomain/;

    include /var/nginx/general/php;
    include /var/nginx/general/upload;
    include /var/nginx/general/error_page_50x;
}
answered Oct 11, 2018 by lina
• 8,110 points

Related Questions In DevOps on Cloud

0 votes
1 answer
+3 votes
2 answers
0 votes
1 answer
0 votes
1 answer

How can I remove a port from url for node app using nginx

If you run your node server on ...READ MORE

answered Apr 10, 2018 in DevOps on Cloud by ajs3033
• 7,280 points
496 views
0 votes
1 answer
+13 votes
2 answers

Git management technique when there are multiple customers and need multiple customization?

Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE

answered Mar 26, 2018 in DevOps & Agile by DragonLord999
• 8,380 points
147 views
+2 votes
2 answers
+2 votes
3 answers

can't make nginx try_files to work with default_index.html

Here's another convenient use of try_files, as ...READ MORE

answered Oct 18, 2018 in DevOps on Cloud by Hannah
• 14,070 points
283 views