如何使用 NGINX 作为反向代理路由第一个 URI 段?

How to route the first URI segment using NGINX as a reverse-proxy?

我正在尝试在 Amazon Web Services 上构建 architecture/infrastructure。今天我有一个像网关一样工作的 EC2,后台有 NGINX。顺便说一句,我是 NGINX 的新手。

上周我有这个 NGINX 配置文件:

server {
    listen 80;

    # I put * for hide the real domain name
    server_name ******.com.ar www.******.com.ar;

    location / {
         proxy_set_header   X-Forwarded-For $remote_addr;
         proxy_set_header   Host $http_host;
         proxy_pass         "http://private.ip.1:80/";
    }
}

而且效果很好!当我转到 www.domain.com.ar 时,我得到一个重定向到端口 80 上的私有 ip 1。

但是,现在我需要稍微调整一下配置文件。

1) 首先,我需要将一些已知路径重定向到私有 ip 1(例如 /company、/portfolio、/services、/contact 和子序列:/company/ourvision、/services/software、/contact/workwithus).我使用的是 NodeJS,而不是 PHP。

2) 如果前面路径中的 none 匹配,我需要将第一个 URI 段作为通配符(例如 http://domain.com.ar/*) matching only this characters: A-z0-9 and send to private ip 2 on port 3000, also I need sending the wildcard word too (ex. http://private.ip.2:3000/wildcard-word

我只是想在第二点上取得成功,但我无法处理它。

server {
    listen 80;
    server_name ******.com.ar www.******.com.ar;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://private.ip.1:80/";
    }

    location ~ ^/(.*)/?$ { 
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://private.ip.2:3000/";
    }
}

但这不起作用。 当我转到 http://example.com.ar 时,我直接转到端口 3000 上的私有 ip 2。顺便说一句,在另一种情况下,当我使用 nginx -t 命令时出现以下错误: "proxy_pass" 不能在正则表达式给定的位置或命名位置

中包含 URI 部分

那么,谁能帮这个菜鸟解决他的问题呢?提前致谢。我将在下面阅读我正在阅读的链接:

您想使用 location / { ... } 块作为您的通配符,因为它匹配任何不匹配另一个 location 块的 URI。

您不需要在 proxy_pass 语句中包含 URI 组件,因为您在向上游发送 URI 之前没有修改它。有关详细信息,请参阅 this document

您可以通过在外部块中指定 proxy_set_header 语句并允许它们被两个 location 块继承来节省键入时间。有关详细信息,请参阅 this document

例如:

proxy_set_header   X-Forwarded-For $remote_addr;
proxy_set_header   Host $http_host;

location ~ ^/(company|portfolio|services|contact|)(/|$) {
    proxy_pass         "http://private.ip.1:80";
}

location / {
    proxy_pass         "http://private.ip.2:3000";
}