Implementing Redirections for Static Sites
This blogs talks about handling redirects in Static Sites
Table of Contents
This approach is a two fold implementation
- Generating pages which redirects the user on client side using javascript
- Implementing Redirects with CDN (This talks about cloudfront)
Generating index.html
for redirects
We generate an index.html page for the redirected paths. This has the below components
http-equiv="refresh"
: The number of seconds until the page should redirect to another - only if the content attribute contains a non-negative integer followed by the string';url='
, and a valid URL.0;url==https://path/to/redirect
: redirects to the given url after 0 seconds.
robots
meta tag, asks the crawlers to not index the page.canonical
link tag: it defines the preferred URL for the current document, which helps search engines reduce duplicate content.- body has a anchor tag, which points to the redirected page
Sample Code
Configuring Redirects with _redirects for supported hosting provider
A lot of hosting providers, supports redirection using _redirects
file.
Eg. For sujeet.pro
, I use cloudflare pages which supports redirection in this way.
The contents of this file is space separated values in format of redirect-from redirect-to
.
Below is the snippet from the redirection configuration used for sujeet.pro
Configuring Redirection for Cloudfront with lambda@edge
If your static site is in S3 and is backed by a Cloudfront CDN, you can use this approach.
Cloudfront supports interceptors using lambda@edge and cloudfront funtions.
- Viewer Request Interceptor (lambda@edge or Cloufront Functions)
- Origin Request Interceptor (only lambda@edge)
- Origin Response Interceptor (only lambda@edge)
- Viewer Response Interceptor (lambda@edge or Cloufront Functions)
We can use lambda@edge function to redirect the users. For data on what urls to redirect and where to redirect, we can deploy a json configuration along with the code.
Redirection using Web Server
If you serve your static files via your won web servers, all the web servers supports redirections.