简体   繁体   English

Nginx 反向代理正则表达式过滤器

[英]Nginx Reverse Proxy Regex Filter

I'm working on migrating a NodeJS reverse proxy over from Apache to Nginx.我正在将 NodeJS 反向代理从 Apache 迁移到 Nginx。 The final things to solve is how to filter my incoming URI for my NodeJS backend.最后要解决的问题是如何过滤我的 NodeJS 后端的传入 URI。

For whatever legacy reason, the NodeJS API responds to URIs like example.com/route/1001 whereas the Apache front end and all client code is actually sending to example.com/api/route/1001 Thus I'm hoping to strip away the /api section of the request URI and send along just the latter half to the Node API.无论出于何种遗留原因,NodeJS API 响应诸如example.com/route/1001之类的 URI,而 Apache 前端和所有客户端代码实际上都发送到example.com/api/route/1001因此我希望剥离/api 部分的请求 URI 并仅将后半部分发送到节点 API。

I was playing around in Regxr trying to get it right and ended up with (?!api)\b\S+ doing well: regexr.com/4lp4e我在 Regxr 中玩耍,试图让它正确,结果(?!api)\b\S+做得很好:regexr.com/4lp4e

However I'm unfamiliar with the Nginx syntax of how I get that into my variable.但是,我不熟悉如何将其放入变量的 Nginx 语法。 Here's what I have right now:这是我现在拥有的:

server {
  server_name <domain>;

  access_log  /var/log/nginx/<domain>-access.log;

  # API endpoint -  (?!api)\b\S+
  location /api {
    if ($request_uri ~* ((?!api)\b\S+) ) {
      set  $last $1;
    }
    add_header X-uri "$last";
    rewrite /api /$last break;
    #proxy_redirect off;
    proxy_pass http://127.0.0.1:4000;
  }

  listen 80;
  listen [::]:80;
}

Try adding a trailing / to the end of your proxy pass:尝试在代理通行证的末尾添加尾随/

proxy_pass http://127.0.0.1:4000/;

Without the trailing / , the full path will be passed:没有尾随/ ,将传递完整路径:
http://127.0.0.1:4000/app/something

With the trailing / , the location pattern, /app , will be replaced with the / :使用尾随/ ,位置模式/app将替换为/
http://127.0.0.1:4000/something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM