Nginx 使用last_path_component 的一部分进行重定向
我根据 URI 中的内容从domain1重定向到domain2,但我需要仅将最后一个路径组件的第一部分传递给domain2。
要重定向的主要入口点为:
https://www.domain1.com/us/type-a-products/**9011-HWD-bolts-new**
新端点:
https://www.domain2.com/us-us/type -a-products/**9011**
所以我只需要考虑第一个连字符之前的最后一个过去组件的第一部分(基本上是产品代码)。
重定向很容易做到:
if ($request_uri ~* "([^/]*$)" ) {
set $last_path_component $1;
}
location ~ /us/type-a-products/(.*) {
return 301 https://www.domain2.com/us-us/type-a-products/$1;
}
但是我如何才能只考虑最后一个路径组件的第一部分(尝试了不同的正则表达式,但我只设法提取最后一个连字符之后的单词)。
任何帮助将不胜感激!
I am redirecting from domain1 to domain2 based on what's present in the URI, but I need to pass to domain2 only the first part of the last path component.
The main entry point to be redirected would be:
https://www.domain1.com/us/type-a-products/**9011-HWD-bolts-new**
new end point:
https://www.domain2.com/us-us/type-a-products/**9011**
So I need to consider only the first part of the last past component before the first hypen (basically the product code).
The redirect is easy to do:
if ($request_uri ~* "([^/]*$)" ) {
set $last_path_component $1;
}
location ~ /us/type-a-products/(.*) {
return 301 https://www.domain2.com/us-us/type-a-products/$1;
}
But how can I consider only the first part of the last path component (tried different regexs but I only managed to extract the word after the last hyphen).
Any help would be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此操作的好地方是在地图中。
它发生在 nginx 周期的早期,并且不会通过以下方式使配置流程短路
介绍正则表达式位置。
服务器配置之外
服务器配置内部
A good place to do this is in a map.
It happens early in the nginx cycle and will not short circuit the flow of your config by
introducing regex locations.
outside of the server config
inside server config
您可以使用
查看正则表达式演示。 详细信息:
([^/-]+)
- 第 1 组:除/
和-
[^/]*
- 除/
之外的任何零个或多个字符$
- 字符串结尾。You can use
See the regex demo. Details:
([^/-]+)
- Group 1: any one or more chars other than/
and-
[^/]*
- any zero or more chars other than/
$
- end of string.