【问题标题】:How do i use NGINX to reverse proxy to local react app我如何使用 NGINX 反向代理到本地反应应用程序
【发布时间】:2021-10-25 11:04:47
【问题描述】:

我正在尝试使用 nginx 为我的本地 react 应用程序做一个简单的反向代理。我无法理解这是如何工作的。我需要location /test 中的根变量还是别名?因为 nginx 正在寻找错误的地址。 (我在 localhost:3001 本地运行我的 react 应用程序)

已经尝试在“location /test”-block 中使用rewrite /test(.*) /$1 break

这是我的 nginx.conf:

server {
    listen 81 ;
    server_name app1.localhost;

    location / {  
        root   html;
        index  index.html index.htm;
    }
    location /test {
        proxy_pass   http://localhost:3001;
    }
}

当我尝试输入 app1.localhost:81/test 时,控制台日志如下:

【问题讨论】:

  • 为什么你有两个location 块(或者,换个问法,你为什么不把proxy_pass 放到/ 位置块中)?
  • 这只是一个实验,我希望/ 只显示来自 nginx 的默认 index.html 文件,/test 显示我的反应应用程序
  • 问题是你的 react 应用不知道它安装在/test 基本路径下。所以你会看到像/static/js/… 这样的请求,实际上需要/test/static/js/… 才能正确解析。
  • 嗯,所以我的 react 应用的静态文件也必须从 nginx 托管?
  • 如果您只为您的应用专门选择一个特定的server_name 并将proxy_pass 放在/ 下,那将是最简单的。您仍然可以拥有默认的 nginx 站点。

标签: nginx reverse-proxy


【解决方案1】:

只需使用两个 server 块:

server {
    listen 81 default_server;

    location / {  
        root html;
        index index.html index.htm;
    }
}

server {
    listen 81;
    server_name app1.localhost;

    location / {  
        proxy_pass http://localhost:3001;
    }
}

【讨论】:

  • 这确实有效,但为什么我不能在两个位置使用相同的服务器?
  • location /test 表示“以 /test 开头的所有内容”。但是您的应用包含像/static/js/… 这样的链接不要 以/test 开头...您基本上需要让您的应用在localhost:3001/test 运行才能使其正常工作。
猜你喜欢
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2020-02-04
  • 2019-08-09
  • 2021-02-04
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多