TTWeb Basics 8. Redirects

Redirects File Contents

The _redirects.yml will be processed and written out to the live site at /_redirects.yaml. This file will be read by cloudfront and processed by lambda-at-edge to return real 301 and 302 style redirect responses.

The structure of _redirects.yml look like

- from/path/:
  to: destination/path/
  code: '301'
- old-path2/[^\?]*(\?.+)?: 
  to: new-path2/$1
  type: regex
  code: '301'

Cloudfront Processing

When a request comes in from cloudfront to the S3 source files, it will take the following steps

  1. Check if the request path needs a ‘/’ appended to the end of it. Requests with extensions will not be modified. Requests that match an existing file exactly will not be modified.
  2. Check the S3 source for the /_redirects.yaml file. If present, compares the request path to all of the options in the file (the first key in each array). The first match will return the to: path with the specified status code. All matching is case-insensitive.
  3. If no matches are made, the request is forwarded on to the S3 source files to return the requested file.

For redirects where type is not regex or regexp, any query strings are preserved in the redirect. e.g. if a request comes in for “/from/path/?param=value”, the following rule will result in a redired to “/destination/path/?param=value”

- from/path/:
  to: destination/path/
  code: '301'

Regular Expression Redirects

When a rediretct is type regex, the matching process assumes the “from” path is a regular expression. Captures are supported. For example, the rule:

- old-path/(.*): 
  to: new-path/$1
  type: regex
  code: '301'

will result in the following redirects:

old-path/ => new-path/ old-path/abc.html => new-path/abc.html old-path/abc/?param=value => new-path/abc/?param=value

For catch-all redirects that don’t include explicit query string captures, you’ll loose query string forwarding. For example

- old-path/.*: 
  to: new-path/
  type: regex
  code: '301'

will result in the following redirects:

old-path/ => new-path/ old-path/abc.html => new-path/ old-path/abc/?param=value => new-path/

To enalbe query string preservation for catch-all redirects, use something like the following:

- old-path/[^\?]*(\?.+)?: 
  to: new-path/$1
  type: regex
  code: '301'

which will result in the following redirects:

old-path/ => new-path/ old-path/abc.html => new-path/ old-path/abc/?param=value => new-path/?param=value