Push state enabled & context path routing: Static assets are not found on the server

戏子无情 提交于 2021-01-27 13:55:22

问题


I deployed a react app to cloud foundry by using the static buildpack. The goal is making the app accessible under domain.com/path. So I configured the route accordingly to his blog post: https://www.cloudfoundry.org/context-path-routing/

Also, I set pushstate: enabled in the static file and added the context path to the static asset URLS; E.g. The URL for the style sheet is domain.com/path/static/style.css. When I visit domain.com/path I get the index.html file. However the static assets which are linked in the index.html file are not found and I get the index file instead. This is the default behaviour for pushstate routing if the resourceis not found on the server.

Is there anything else I need to configure in order to run the app with pushstate: enabled in a 'subdirectory'?


回答1:


When you enable push state with pushstate: enabled, the Nginx configuration that is assembled by the buildpack for your app will look roughly like this. I've also highlighted the section that's added specifically to address push state.

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;

    }
}

You can see the code in the buildpack that enables this here.

I think the short answer is that the buildpack is assuming you're running out of the root and not a sub-directory, which is what happens when you use Cloud Foundry's path based routing.

To work around this, you just need to manually enable the same or similar Nginx configuration. To do that I'd recommend the following:

  1. Enable Custom Location Configuration. See the column in the table at that link which has that name & follow those instructions. This gives me the following Staticfile.

    root: public
    location_include: includes/*.conf
    

    Note that this requires all the static files to serve up to be under a folder called public (or whatever you want to name the root folder of your files). You have to do this when using location_include.

  2. Add a custom includes file nginx/conf/includes/push_state.conf and inside the file add the following.

    location /path/ {
    
        if (!-e $request_filename) {
          rewrite ^(.*)$ /path/ break;
        }
    
        index index.html index.htm Default.htm;
    
    }
    
  3. Push your app. It should deploy and run with the custom code added to the base Nginx configuration used by your buildpack.

Hope that helps!



来源:https://stackoverflow.com/questions/47051132/push-state-enabled-context-path-routing-static-assets-are-not-found-on-the-se

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!