Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx variable for subdomain?

Tags:

redirect

nginx

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

like image 412
KEINOS Avatar asked Jul 26 '17 06:07

KEINOS


Video Answer


1 Answers

You can use a regular expression in the server_name to extract the part you need as a named capture. For example:

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

See this document for more.

like image 123
Richard Smith Avatar answered Oct 19 '22 15:10

Richard Smith