Skip to content

Rewrite #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 28 additions & 9 deletions url-rewrite-single-page-apps/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
/**
* Given a URI this will return the suffix which should be appended in cases where the URI does not include a filename or extension.
* @see https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/url-rewrite-single-page-apps
*/
function uriSuffix(uri) {
// Iterate over the given URI in reverse order looking for '/' or '.' as a means to determine if the
// last path element represents a file (indicated by a file extension).
var count = uri.length - 1;
for (var indx = count; indx >= 0; --indx) {
var achar = uri[indx];
// If we find a '/' append 'index.html' as the last path element
if (achar === '/') {
return indx === count ? 'index.html' : '/index.html';
}
// Otherwise if we find a '.' we assume the last path element is a file and return empty string
// (no URI modification needed).
else if (achar === '.') {
return '';
}
}

// If we did not encounter a '/' or '.', default.
return '/index.html';
}

function handler(event) {
var request = event.request;
var uri = request.uri;

// Check whether the URI is missing a file name.
if (uri.endsWith('/')) {
request.uri += 'index.html';
}
// Check whether the URI is missing a file extension.
else if (!uri.includes('.')) {
request.uri += '/index.html';
var suffix = uriSuffix(request.uri);
if (suffix.length) {
request.uri += suffix;
}

return request;
Expand Down