在 nginx 中使用正则表达式重定向子域

编程入门 行业动态 更新时间:2024-10-13 16:22:39
本文介绍了在 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.

我希望 subdomain.mydomain 重定向到 mydomain/subdomain

这是我的代码.

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

另外,可能值得注意.在 nginx 配置文件的更下方有一条规则:

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

server { server_name *.mydomain ... }

我做错了什么?

更新:

有人建议我不要为此使用正则表达式......以提供更清晰的信息:琐碎的正则表达式只是为了排除故障.真正的正则表达式看起来更像是...

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 ^ fakeairport/cincinnati; } server { server_name "~^.*(lex|lexington).fakeairport(app)?.(org|com)$"; rewrite ^ fakeairport/lexington; }

所以最好使用正则表达式.

So it would be preferable to use regex.

推荐答案

回答一个老问题以帮助他人

To answer an old question to help others

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

using nginx 1.1.19 you can do the following:

server { server_name ~^(?<subdomain>w+).domainA$; location / { rewrite ^ $subdomain.domainB$request_uri permanent; } }

domainA 之前的子域匹配并存储在变量 $subdomain 中,然后可以在重写中使用.这将像 xxx.domainA 这样的 url 重写为 xxx.domainB,并且只有一个服务器指令.

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

更多推荐

在 nginx 中使用正则表达式重定向子域

本文发布于:2023-10-31 13:41:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   正则表达式   nginx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!