You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用正则表达式替代变量实现NGINX URI重写的问题求助

使用正则表达式替代变量实现NGINX URI重写的问题求助

各位大佬好,我现在碰到个NGINX URI重写的难题,想请教下大家的思路。

我原本的需求是把收到的类似http://core/api/token这类请求URI,重写成http://token。之前通过在location块里定义变量的方式已经成功实现了:

rewrite ${INBOUND_ENDPOINT} ${REDIRECT_ENDPOINT} break;

但现在要求我改用if语句配合正则表达式,提取请求URI的最后一部分来完成重写,就像上面的例子里只保留/token这部分。试了好几种写法都没搞定,有没有懂行的大佬能帮忙指点下?提前谢过大家了!


更新:
我尝试了下面这段配置,但还是没达到预期效果,麻烦帮忙看看哪里出问题了:

server {
  listen 80;
  server_name example.com;

  # Handle favicon.ico requests separately to prevent unwanted redirects
  location = /favicon.ico {
    return 204;
  }

  location / {
    # Use an if statement to match and capture the final part of the path
    if ($request_uri ~* ^.*/([^/]+)$) {
      # Rewrite the URI to use only the final part of the path
      set $final_part $1;
      rewrite ^ /$final_part break;
    }
  }
}

备注:内容来源于stack exchange,提问作者tony_tee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 10:40:30