Nginx 反向代理节点应用 API

Nginx reverse proxy to node application API

我的服务器上有一个 NGINX 反向代理处理 http://apcompdoc.com. It listens on port 80, and can successfully return the Vue Dist, however, I have a backend node API running on port 8081 and another node process running on port 8082. The user never directly requests anything on 8082, but rather the process on 8081 sometimes requests the process on 8082, so I'm assuming I never have to even expose that to Nginx at all, but I'm not too sure. However, the main problem is that the API is never reached I believe. I have it so that when you hit the endpoint http://apcompdoc.com/api/* 它应该代理到节点进程。我正在使用 PM2 来使进程保持活动状态并对其进行监控,并确信它是 运行。这是我的 NGINX apcompdoc.com 配置文件:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    server_name: apcompdoc.com www.apcompdoc.com;
    charset utf-8;
    root    /var/www/apcompdoc/dist;
    index    index.html index.htm;
    # Always serve index.html for any request;
    location / {
        root /var/www/apcompdoc/dist;
        try_files $uri /index.html;
    }
    location /api/ {
        proxy_pass http://localhost:8081;
    }
    error_log /var/log/nginx/vue-app-error.log;
    access_log /var/log/nginx/vue-app-access.log;
}

我正在尝试让我的 API 在 /api/* 的所有请求重定向到 API 在 localhost:8081 然后返回给用户.我看到了有关将代理重定向回来的内容,我必须这样做吗?我也不知道我是否必须在 NGINX 配置文件中执行 /api/*。 我是 NGINX 的新手,但我只想将对 http://apcompdoc.com/api/* 的请求重定向到端口 8081 上的节点进程。

不好或好的做法,我不确定,但我总是将我的后端定义为 upstream。 例如,您的文件将如下所示:

upstream nodeprocess {
    server localhost:8081;
}
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    server_name: apcompdoc.com www.apcompdoc.com;
    charset utf-8;
    root    /var/www/apcompdoc/dist;
    index    index.html index.htm;
    # Always serve index.html for any request;
    location / {
        root /var/www/apcompdoc/dist;
        try_files $uri /index.html;
    }
    location  ^~ /api {
        proxy_pass http://nodeprocess;
    }
    error_log /var/log/nginx/vue-app-error.log;
    access_log /var/log/nginx/vue-app-access.log;
}

请注意我在 api 的位置添加了 ^~ 并删除了尾随 /