启用推送状态和上下文路径路由:在服务器上找不到静态资产
Push state enabled & context path routing: Static assets are not found on the server
我使用静态构建包将 React 应用程序部署到 Cloud Foundry。目标是使应用程序可在 domain.com/path 下访问。所以我根据他的博客post配置了路由:https://www.cloudfoundry.org/context-path-routing/
此外,我在静态文件中设置了pushstate: enabled
,并将上下文路径添加到静态资源URLS;例如。样式 sheet 的 URL 是 domain.com/path/static/style.css
。
当我访问 domain.com/path 时,我得到了 index.html 文件。但是,找不到 index.html 文件中链接的静态资产,我得到的是索引文件。如果在服务器上找不到资源,这是推送状态路由的默认行为。
为了 运行 在 'subdirectory' 中使用 pushstate: enabled
的应用程序,我还需要配置什么吗?
当您使用 pushstate: enabled
启用推送状态时,由 buildpack 为您的应用组装的 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;
}
}
您可以在 buildpack 中看到启用此功能的代码 here。
我认为简短的回答是 buildpack 假设您运行离开根目录而不是子目录,当您使用 Cloud Foundry 的基于路径的路由时会发生这种情况。
要解决此问题,您只需手动启用相同或相似的 Nginx 配置。为此,我推荐以下内容:
启用Custom Location Configuration。请参阅 table 中具有该名称的 link 中的列并按照这些说明进行操作。这给了我以下 Staticfile
.
root: public
location_include: includes/*.conf
请注意,这需要所有静态文件都位于名为 public
的文件夹(或您想要命名文件根文件夹的任何名称)下。使用 location_include
.
时必须这样做
添加自定义包含文件 nginx/conf/includes/push_state.conf
并在文件中添加以下内容。
location /path/ {
if (!-e $request_filename) {
rewrite ^(.*)$ /path/ break;
}
index index.html index.htm Default.htm;
}
推送您的应用。它应该部署并 运行 将自定义代码添加到您的构建包使用的基本 Nginx 配置中。
希望对您有所帮助!
我使用静态构建包将 React 应用程序部署到 Cloud Foundry。目标是使应用程序可在 domain.com/path 下访问。所以我根据他的博客post配置了路由:https://www.cloudfoundry.org/context-path-routing/
此外,我在静态文件中设置了pushstate: enabled
,并将上下文路径添加到静态资源URLS;例如。样式 sheet 的 URL 是 domain.com/path/static/style.css
。
当我访问 domain.com/path 时,我得到了 index.html 文件。但是,找不到 index.html 文件中链接的静态资产,我得到的是索引文件。如果在服务器上找不到资源,这是推送状态路由的默认行为。
为了 运行 在 'subdirectory' 中使用 pushstate: enabled
的应用程序,我还需要配置什么吗?
当您使用 pushstate: enabled
启用推送状态时,由 buildpack 为您的应用组装的 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;
}
}
您可以在 buildpack 中看到启用此功能的代码 here。
我认为简短的回答是 buildpack 假设您运行离开根目录而不是子目录,当您使用 Cloud Foundry 的基于路径的路由时会发生这种情况。
要解决此问题,您只需手动启用相同或相似的 Nginx 配置。为此,我推荐以下内容:
启用Custom Location Configuration。请参阅 table 中具有该名称的 link 中的列并按照这些说明进行操作。这给了我以下
Staticfile
.root: public location_include: includes/*.conf
请注意,这需要所有静态文件都位于名为
public
的文件夹(或您想要命名文件根文件夹的任何名称)下。使用location_include
. 时必须这样做
添加自定义包含文件
nginx/conf/includes/push_state.conf
并在文件中添加以下内容。location /path/ { if (!-e $request_filename) { rewrite ^(.*)$ /path/ break; } index index.html index.htm Default.htm; }
推送您的应用。它应该部署并 运行 将自定义代码添加到您的构建包使用的基本 Nginx 配置中。
希望对您有所帮助!