Nginx variable for subdomain?

Viewed 13061

I need a Guru's advice.

On Nginx's conf file, I would like to get the subdomain as a variable in order to redirect accesses as follow.

  • ACCESS: http://userX.example.com/?hoo=bar
  • REDIRECT: http://example.com/userX/?hoo=bar

But I get

  • REDIRECT: http://example.com/userX.example.com/?hoo=bar

My current _http.conf settings are like below. So obviously it works so.

## default HTTP
server {
    listen       80;
    server_name  default_server;
    return       301 http://example.com/$host$request_uri;
}

Are there any vaiables or ways to do like below?

## default HTTP
server {
    listen       80;
    server_name  default_server;
    return       301 http://example.com/$subdomain$request_uri;
}

I know if the subdomain part is limited it can be redirected, but I have to add them each time and I want it to keep as simple as possible.

Is there any simple way to do so?

[ENV]: CentOS:7.3.1611, nginx: nginx/1.13.3, *.example.com is targetted to the same server in NS settings.


Conclusion (2017/12/13)

Use a regular expression:

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

Ref: Comment, Document

1 Answers
Related