amazon-s3dnssubdomainwildcard-subdomainstatic-pages

AWS static website - how to connect subdomains with subfolders


I want to setup S3 static website and connect with my domain (for example domain: example.com).

In this S3 bucket I want to create one particular folder (name content) and many different subfolders with in, then I want to connect these subfolders with appropriate subdomains, so for example

Any content subfolder should be automatically available from subdomain with that same prefix name like folder name. I will be grateful for any possible solutions for this problem. Should I use redirection option or there is any better solution? Thanks in advance for help.


Solution

  • My solution base on this video: https://www.youtube.com/watch?v=mls8tiiI3uc

    Because above video don’t explain subdomain problem, here is few additional things to do:

    'use strict';
    
     exports.handler = (event, context, callback) => {
         const path = require("path");
    
        const remove_suffix = ".domain.com";
        const host_with_www = "www.domain.com"
        const origin_hostname = "www.domain.com.s3-website.eu-west-1.amazonaws.com";
        const request = event.Records[0].cf.request;
        const headers = request.headers;
        const host_header = headers.host[0].value;
        if (host_header == host_with_www) {
            return callback(null, request);
        }
        if (host_header.startsWith('www')) {
            var new_host_header = host_header.substring(3,host_header.length)
        }
        if (typeof new_host_header === 'undefined') {
            var new_host_header = host_header
        } 
        if (new_host_header.endsWith(remove_suffix)) {
            // to support SPA | redirect all(non-file) requests to index.html
            const parsedPath = path.parse(request.uri);
            if (parsedPath.ext === "") {
            request.uri = "/index.html";
            }
            request.uri =
            "/" +
            new_host_header.substring(0, new_host_header.length - remove_suffix.length) +
            request.uri;
        }
    
        headers.host[0].value = origin_hostname;
        return callback(null, request);
        
    };