如何在 AWS EC2 上使用 Node.js 后端在 Nginx 上运行 React 应用程序?

wri*_*wan 4 nginx node.js reactjs nginx-location nginx-config

我正在尝试在 Nginx 服务器上运行带有 Node.js 后端的 React 应用程序。

这是 nginx.conf 文件中我的服务器块:

include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/folder-name/frontend/build;
        index index.html index.htm;

        location / {
                proxy_pass http://localhost:5000;
        }
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;



        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
Run Code Online (Sandbox Code Playgroud)

build文件夹包含编译后的react js代码(使用npm run build) Node.js 后端使用 pm2/forever 在端口 5000 上运行。

重启Nginx服务器后,服务器IP上出现react UI,但UI扭曲。另外,我无法访问我的后端 APIMyIP/api/endpoint.

我究竟做错了什么。?这个 nginx 配置是根据 SO 和其他在线资源构建的,因此很有可能是错误的。请帮忙!

提前致谢!

Nam*_*ran 7

问题是您正在为根 ( /) 设置 API 代理。正确的应该是这样的:

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/folder-name/frontend/build;
        index index.html index.htm;

        location /api {
            proxy_pass http://localhost:5000;
        }

        location / {
            try_files $uri $uri/ =404;
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果你的 Node.js 中没有/api路径,你将需要一个重写规则,如下所示:

        location /api {
            rewrite ^/api/?(.*) /$1 break;
            proxy_pass http://localhost:5000;
            proxy_redirect     off;
            proxy_set_header   Host $host; 
        }
Run Code Online (Sandbox Code Playgroud)