Nginx 使用last_path_component 的一部分进行重定向

发布于 2025-01-13 17:04:21 字数 818 浏览 1 评论 0原文

我根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何处潇湘 2025-01-20 17:04:21

执行此操作的好地方是在地图中。
它发生在 nginx 周期的早期,并且不会通过以下方式使配置流程短路
介绍正则表达式位置

服务器配置之外

map $uri $redirect_id_uri {
    ~^/us/type-a-products/\*\*(?<id>\d+)-.*\*\*$ https://www.domain2.com/us/type-a-products/**$id**;
}

服务器配置内部

if ($redirect_id_uri) {
    return 301 $redirect_id_uri;
}

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

map $uri $redirect_id_uri {
    ~^/us/type-a-products/\*\*(?<id>\d+)-.*\*\*$ https://www.domain2.com/us/type-a-products/**$id**;
}

inside server config

if ($redirect_id_uri) {
    return 301 $redirect_id_uri;
}
夜声 2025-01-20 17:04:21

您可以使用

([^/-]+)[^/]*$

查看正则表达式演示详细信息

  • ([^/-]+) - 第 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文