启用推送状态和上下文路径路由:在服务器上找不到静态资产

问题描述 投票:0回答:2

我使用静态构建包将 React 应用程序部署到 Cloud Foundry。目标是使应用程序可以在domain.com/path下访问。所以我根据他的博客文章配置了路线:https://www.cloudfoundry.org/context-path-routing/

此外,我在静态文件中设置了

pushstate: enabled
并将上下文路径添加到静态资源 URLS 中;例如。样式表的 URL 是
domain.com/path/static/style.css
。 当我访问domain.com/path 时,我得到了index.html 文件。但是,找不到 index.html 文件中链接的静态资源,而是找到了索引文件。如果在服务器上找不到资源,这是推送状态路由的默认行为。

enter image description here

我还需要配置什么才能在“子目录”中使用

pushstate: enabled
运行应用程序吗?

routes cloud-foundry pushstate swisscomdev
2个回答
7
投票

当您使用

pushstate: enabled
启用推送状态时,构建包为您的应用程序组装的 Nginx 配置将大致如下所示。 我还突出显示了专门为解决推送状态而添加的部分。

server {
    listen 8080;
    server_name localhost;

    root /home/vcap/app/public;

    location / {
        # <-- this bit here is what's added for push state support
        if (!-e $request_filename) {
          rewrite ^(.*)$ / break;
        }
        #  -->

        index index.html index.htm Default.htm;

    }
}

您可以在构建包中看到启用此功能的代码here

我认为简短的答案是构建包假设您用完了根目录而不是子目录,这就是当您使用 Cloud Foundry 的基于路径的路由时会发生的情况。

要解决此问题,您只需手动启用相同或相似的 Nginx 配置即可。 为此,我建议如下:

  1. 启用自定义位置配置。 请参阅该链接中具有该名称的表中的列并按照这些说明进行操作。 这给了我以下

    Staticfile

    root: public
    location_include: includes/*.conf
    

    请注意,这要求所有静态文件都位于名为

    public
    的文件夹下(或任何您想要命名的文件根文件夹)。 使用
    location_include
    时必须这样做。

  2. 添加自定义包含文件

    nginx/conf/includes/push_state.conf
    并在文件内添加以下内容。

    location /path/ {
    
        if (!-e $request_filename) {
          rewrite ^(.*)$ /path/ break;
        }
    
        index index.html index.htm Default.htm;
    
    }
    
  3. 推送您的应用程序。它应该使用添加到构建包使用的基本 Nginx 配置中的自定义代码进行部署和运行。

希望有帮助!


0
投票

在反应中,如果您在

.env-cmdrc
文件中使用 "PUBLIC_URL": "/path",则在您的 index.html 中,所有 js 和静态内容都将具有 /path/ 上下文。当它尝试加载这些文件时,它将失败,或者在您的情况下,它会返回index.html。因为在 PCF (Ngnix) 中,您的文件已部署在根目录 (domain.com/) 中。如果您尝试访问没有“路径”的文件,它将起作用。例如:domain.com/static/style.css。要解决此问题,您需要修改 PCF Ngnix 配置。

静态文件的内容

root: public
location_include: includes/*.conf

anything.conf
 中创建文件 
yourbuild-folder/nginx/conf/includes

anything.conf 的内容

#Serve all files under domain.com/path/anything for domain.com/anything path
location ~* ^/path/(.*)$ {
        rewrite ^/path/(.*)$ /$1 break;
        try_files $uri =404;
    }

注意:如果您看到静态文件内容,则

root
您需要将构建工件放在公共(您可以重命名为任何内容)文件夹中。

构建文件夹结构:

build
 |
 |_/public/
 |        |_static/style.css
 |        |_index.html
 |        |_favicon.ico
 |
 |_Staticfile
 |
 |_/nginx/conf/includes/
                       |_anything.conf
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.