Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

regex - Redirecting a subdomain with a regular expression in nginx

The nginx documentation says that the server_name directive supports regular expressions. I've been banging my head against the wall trying to get even a trivial regex working.

I want http://subdomain.mydomain.com to redirect to http://mydomain.com/subdomain

Here is my code.

server {
  server_name "~^subdomain.mydomain.com$";
  rewrite ^ http://mydomain.com/subdomain;
}

Also, potentially noteworthy. Further down in the nginx config file there is a rule:

server {
  server_name *.mydomain.com
  ...
}

What am I doing wrong?

UPDATE:

It has been suggested that I not use regex for this... to offer a little more clarity: the trivial regex was simply for purposes of troubleshooting. The real regex will look more like...

server {
  server_name "~^.*(cvg|cincinnati).fakeairport(app)?.(org|com)$";
  rewrite ^ http://fakeairport.com/cincinnati;
}

server {
  server_name "~^.*(lex|lexington).fakeairport(app)?.(org|com)$";
  rewrite ^ http://fakeairport.com/lexington;
}

So it would be preferable to use regex.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To answer an old question to help others

using nginx 1.1.19 you can do the following:

server {
    server_name     ~^(?<subdomain>w+).domainA.com$;

    location / {
            rewrite ^ https://$subdomain.domainB.com$request_uri permanent;
    }
}

The subdomain before domainA.com is matched and stored in variable $subdomain which then can be used in the rewrite. This rewrites url like xxx.domainA.com to xxx.domainB.com with only one server directive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...