Reputation: 1392
When I try to access a JavaScript file hosted on Cloud Foundry using the Staticfile Buildpack, my browser refuses to load it and displays an error message in the console:
Access to script at ‘…’ from origin ‘…’ has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
How do I configure cross-origin resource sharing (CORS) in the Cloud Foundry Staticfile Buildpack?
Upvotes: 3
Views: 4889
Reputation: 1392
Create a file named Staticfile
with the following contents:
root: public
location_include: includes/*.conf
Ensure that the files you want your app to serve are located in the public
folder.
Create the file nginx/conf/includes/headers.conf
(with its parent folders) with the following contents:
add_header 'Access-Control-Allow-Origin' '*';
That's it! After your next cf push
, the CORS header will be set.
For more clarity, see also the official code sample include_headers_public
.
As of the Staticfile Buildpack documentation:
If you create a file named
Staticfile
and locate it in the build directory of your app, Cloud Foundry automatically uses the Staticfile buildpack when you push your app.
(It means you don't need to specify the staticfile_buildpack
in your manifest.yml
)
Then follow the instructions under Custom Location
.
Custom Location allows you to specify custom location definitions with additional directives.
To customize the location block of the NGINX configuration file, follow the steps below.
- Set an alternative
root
directory. Thelocation_include
property only works in conjunction with an alternativeroot
.
- Create a file with location-scoped NGINX directives. See the following example, which causes visitors of your site to receive the
X-MySiteName
HTTP header:
- File:
nginx/conf/includes/custom_header.conf
- Content:
add_header X-MySiteName BestSiteEver;
Set the
location_include
variable in your Staticfile to the path of the file from the previous step. This path is relative tonginx/conf
.Example:
root: public location_include: includes/*.conf
Upvotes: 7
Reputation: 930
A bit of history - This got implemented to the Static Build Pack via this story - https://www.pivotaltracker.com/n/projects/1042066/stories/136370663
A similar issue was raised against the BuildPack team - https://github.com/cloudfoundry/staticfile-buildpack/issues/89
Refer to the below sample App on how to configure any additional custom headers - https://github.com/cloudfoundry/staticfile-buildpack/tree/master/fixtures/include_headers_public
You can then additionally add CORS specific response headers as well (allowed hosts & allowed methods)
Upvotes: 0