Nginx位置正则表达式捕获变量

时间:2015-10-12 11:01:25

标签: regex nginx http-proxy

我有这个REST API URL:

http://localhost:4000/api/v2/stocks/accounts/1162/tradings

我想将它代理到URL:

http://localhost:4001/api/v2/stocks/accounts/1162/tradings

其中1162是URL参数,可以是其他值。

我有以下内容:

location ^~ /api/v2/stocks/accounts/([^/]+)/tradings {
      proxy_pass http://localhost:4001/api/v2/stocks/accounts/$1/tradings;
}

但它不起作用(404 Not Found),我搜索了类似的问题,但没有多大帮助:

喜欢这个:Get arguments Nginx and path for proxy_pass或者这个:trouble with location regex and redirection in nginx

有没有办法实现我想要的,使用nginx?

提前感谢您的帮助。

增加:

我还添加了参数捕获:

location ~ /api/v2/stocks/accounts/([^/]+)/tradings/(.*) {
    proxy_pass http://localhost:4001/api/v2/stocks/accounts/$1/tradings/$2$is_args$args;
}

1 个答案:

答案 0 :(得分:3)

你可以这样做。不是' ^〜'

location ~ /api/v2/stocks/accounts/([^/]+)/tradings {
  proxy_pass http://localhost:4001/api/v2/stocks/accounts/$1/tradings;
}

nginx.org所述 ^〜通常与目录匹配,如下所示:

location ^~ /dir/ {
    # some actions
}
相关问题