为什么我的Nginx将我的应用程序静态文件路由到我的index.html

时间:2020-09-12 13:21:12

标签: reactjs nginx

我想在我的域的子路由上托管一个演示应用程序。当我将应用程序放置在域的根目录并使用以下配置时,它会起作用:

server {
   server_name domain.com www.domain.com;
   root /var/www/my-app/build;
   index index.html index.htm;
   location / {
       try_files $uri /index.html =404;
   }
}

但是当我使用以下配置将其移动到子路由时,它会正确获取初始index.html,然后将静态文件请求(用于CSS,JS,图像...)也路由到index.html。 / p>

server {
        listen 80;
        server_name domain.com www.domain.com;

        location / {
        }
        location /demo-apps/my-app{
                root /var/www/my-app/build;
                try_files $uri /index.html =404;
        }
}

我不明白为什么。这是请求的屏幕截图,该请求成功,但返回js文件的index.html文件instad:

enter image description here

这是服务器上的文件夹结构:

enter image description here

据我了解,第一个屏幕截图中的请求应与第二个位置块中的$ uri条件匹配,并返回相应的js文件,但是显然,我错了。我需要进行哪些更改才能使其正常工作?

在有人问之前,是的,我确实重启了nginx。

1 个答案:

答案 0 :(得分:1)

通过将root的值与$uri的值连接来构造文件的路径。因此,将在错误的位置/demo-apps/my-app/css/foo.css查找对/var/www/my-app/build/demo-apps/my-app/css/foo.css的请求。

您可以改为使用alias(请参阅this document),例如:

location /demo-apps/my-app {
    alias /var/www/my-app/build;
    try_files $uri /demo-apps/my-app/index.html;
}

但是,同时使用aliastry_files可能会有问题。参见this long term issue


或使用正则表达式location(请参阅this dcoument)提取URI的后半部分,例如:

location ~ ^/demo-apps/my-app(/.*)?$ {
    root /var/www/my-app/build;
    try_files $1 /index.html =404;
}