在Nginx中使用正则表达式重定向子域 [英] Redirecting a subdomain with a regular expression in nginx

查看:63
本文介绍了在Nginx中使用正则表达式重定向子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

nginx文档说 server_name指令支持正则表达式.我一直把头撞在墙上,试图使琐碎的正则表达式正常工作.

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.

我希望 http://subdomain.mydomain.com 重定向到这是我的代码.

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

此外,可能值得注意.在nginx的配置文件中,还有一个规则:

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

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

我在做什么错了?

更新:

已建议我不要为此使用正则表达式...以便提供更多的清晰度:琐碎的正则表达式只是出于故障排除的目的.真正的正则表达式看起来更像是...

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.

推荐答案

回答旧问题以帮助他人

使用nginx 1.1.19,您可以执行以下操作:

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;
    }
}

domainA.com之前的子域被匹配并存储在变量$ subdomain中,然后可以在重写中使用它. 这仅用一个服务器指令将xxx.domainA.com之类的网址重写为xxx.domainB.com.

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.

这篇关于在Nginx中使用正则表达式重定向子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆