使用 nginx 反向代理在一个域上隐藏节点应用程序端口号

Hiding Node app port numbers on one domain with nginx reverse proxy

我仍然是 nginx 的初学者,希望能得到一些帮助和澄清我正在做的事情。

假设我有 2 个节点应用程序,app1app2

我有一个生产服务器,但我想先在本地测试它。

目前 app1 侦听端口 8000,app2 侦听端口 8001。

所以目前,它们位于 localhost:8000localhost:8001,并且会在生产服务器中作为 production.example.com:8000production.server.com:8001 访问。

我的问题是,如何隐藏端口号并将它们分配给特定的 URL?

我希望可以从生产服务器中的 localhost/app1localhost/app2 以及 production.example.com/app1production.server.com/app2 访问结果。

我不知道我在 nginx.conf 中犯了什么错误,所以我希望有人能帮助我解决这个问题。这些应用程序都有 HTML 形式,所以我需要它们 post 到 production.example.com/app1 或类似 production.example.com/app2/download 的东西。由于每个应用程序中 public 文件夹的位置,它们的 CSS 也会中断,因为它们仅在 /public/css.css 中,而不在 app2/public/css.css.

我可以通过在 Node 应用程序中分别添加 /app1/app2 来更改所有表单操作和路由器 gets/posts,以及样式表引用,但感觉就像我做错了什么,因为我不应该更改我的任何路由器信息。

这是我的 nginx.conf 文件:

编辑:这就是我现在拥有的:

server {
        # ...

        location /app1 {
                rewrite ^/app1$ / break;
                rewrite ^/app1/(.*) / break;
                proxy_pass      http://127.0.0.1:8000;
        }

        location /app2 {
                rewrite ^/app2$ / break;
                rewrite ^/app2/(.*) / break;
                proxy_pass      http://127.0.0.1:8001;
        }
}

我仍然遇到同样的问题,即节点应用程序本身没有使用它们的上下文。

所以,我有 4-5 个微服务的相同配置。这是我使用的配置。

server {

    listen       80;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;
    location /ifttt {
        rewrite ^/ifttt$ / break;
        rewrite ^/ifttt/(.*) / break;
        proxy_pass http://127.0.0.1:8080;
    }
    location /actions {
        rewrite ^/actions$ / break;
        rewrite ^/actions/(.*) / break;
        proxy_pass http://127.0.0.1:5000;
    }
    location /events {
        rewrite ^/events$ / break;
        rewrite ^/events/(.*) / break;
        proxy_pass http://127.0.0.1:5050;
    }
    location / {
        proxy_pass http://127.0.0.1:8081;
    }
}

希望能起到建设性的参考作用。来一张吧,

location /actions {
    rewrite ^/actions$ / break;
    rewrite ^/actions/(.*) / break;
    proxy_pass http://127.0.0.1:5000;
}

因此,第一次重写仅匹配 localhost/actions 并将其转发给 http://127.0.0.1:5000 第二个匹配localhost/actions/<anything>并转发给http://127.0.0.1:5000/<anything>

我认为您在正则表达式匹配之前遗漏了斜杠 (/)。

编辑:

以您的评论为参考

索引位于/app1/index
页面位于 /app1/index/flashfireblast
导航栏 header 需要引用 /app1/stylesheets/css.css

因此,要从 /app1/index/flashfireblast 解决 /app1/stylesheets/css.css,您需要添加 ../stylesheets/css.css 作为样式表 href。

供参考:
如果当前目录是 /var/www
1) /:表示Root。 /
2) ./:表示当前目录。 /var/www
3) ../:表示上一级目录。 /var/