
Application Performance - HTTP redirections management
Redirection management is a common requirement on websites, often used to redirect non existing URLs, or to localize content based on country.
- How frequently do you update your redirection logic? Heavy usage of redirections in parallel by different teams, requires a more sophisticated implementation compared to simpler, occasional A/B testing.
- How many redirection rules do you have in your logic? The size of the redirections database is a factor to be considered when evaluating different storage options.
- Are redirections static or dynamic (e.g. varies based on user country or device capabilities)? When it's dynamic, redirection logic should be executed in a context where all necessary parameters are available to vary the response.
- Do you rewrite the URL transparently to the user, or send a 3xx Redirection?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function handler(event) {
var request = event.request;
var headers = request.headers;
var host = request.headers.host.value;
var supported_countries = ['ie','ae', 'es']; // countries in which you'd like to serve a localized version of your Single Page Application
var defaultCountryIndex = 0; // default country index in the support_countries array. here it is 'ie'
if ((supported_countries.includes(request.uri.substring(1,3))) && ((request.uri.substring(3,4) === '/') || (request.uri.length === 3))) {
// If one of the supported country codes is included in the path (e.g. /es/about) then add index.html when needed to the reauest
return requestWithIndexHTML(request);
} else if ((headers['cloudfront-viewer-country']) && (headers['cloudfront-viewer-country'].value.toLowerCase() !== supported_countries[defaultCountryIndex])){
// Otherwise if the user reauest is coming from one of the supported countries except the default one, then redirect to country specific version (e.g. /about -> /es/about)
var response = {
statusCode: 302,
statusDescription: 'Found',
headers: { location: { value: `https://${host}/${headers['cloudfront-viewer-country'].value.toLowerCase()}${request.uri}` } },
};
return response;
} else {
// Otherwise send rewrite the request to the default country path, add index.html if needed and return
request.uri = '/'+supported_countries[defaultCountryIndex] + request.uri;
return requestWithIndexHTML(request);
}
}
// Add index.html to SPA path when needed
function requestWithIndexHTML(request) {
if (request.uri.endsWith('/')) {
request.uri += 'index.html';
} else if (!request.uri.includes('.')) {
request.uri += '/index.html';
}
return request;
}
Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.