Prevent Cloudfront from forwarding part of path to origin server
CloudFront doesn't natively support this.
The original request path is forwarded intact to the origin server, with only one exception: if the origin has an Origin Path configured, that value is added to the beginning of the path before the request is sent to the origin (and, of course, this doesn't help, here).
However, you can modify the path during CloudFront processing using a Lambda@Edge Origin Request trigger.
This type of trigger fires only on cache misses -- after the CloudFront cache is checked but before the request is sent to the origin -- and allows modification of the request that will be sent to the origin... including the path. The response from the origin, if cacheable, is stored in CloudFront under the path originally requested by the browser (not the modified path), so caching still works correctly even when the trigger modifies the path.
The trigger code to remove the first level from the path might look something like this:
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request; // extract the request object
request.uri = request.uri.replace(/^\/[^\/]+\//,'/'); // modify the URI
return callback(null, request); // return control to CloudFront
};
There's more discussion of this in my answer to a very similar question at Stack Overflow, which is the original source of the code snippet above. It was originally written in Node.js 6.10 but is still compatible with the Lambda@Edge interface, which now uses newer versions of Node. Alternately, if you prefer, the trigger code can also be written in Python.
You might also need to arrange for /subfolder
to be redirected to /subfolder/
so that paths relative to the root of the second origin are correctly canonicalized.