Skip to content
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

Redirect naked to www example #5

Open
719media opened this issue May 12, 2021 · 2 comments
Open

Redirect naked to www example #5

719media opened this issue May 12, 2021 · 2 comments

Comments

@719media
Copy link

It would be helpful for me to have an example of how to redirect naked to www (e.g. requests to domain.com should 301 to www.domain.com). When migrating from lambda@edge to cloudfront functions, some things seemed to change, like the structure of the "event" parameter, and it was a little confusing to me at first.

I'm also not sure if best practice is that it's more efficient/cheaper to use lambda@edge Origin Request for this type of an operation (because it can then be cached for a long time on subsequent requests), or cloudfront function Viewer Request.

Thanks

@bjarneo
Copy link

bjarneo commented May 14, 2021

Hey, @719media, they kind of have an example at the redirect-based-on-country folder.

I did a quick rewrite, and I assume this is what you are looking for?

Please do verify the output of the host before deploying this to production to be sure you get the correct value.

function handler(event) {
    var host = event.request.headers.host.value;

    if (host !== 'example.com') {
        return event.request;
    }

    return {
        statusCode: 301,
        headers: { 
            location: { 
                value: 'https://www.example.com' 
            } 
        }
    };
}

I can create a PR for an example folder if that is something people find useful.

Cheers 🥂

@719media
Copy link
Author

Ya, that's more or less what I came up with. I was just looking for the example's presence from library author as proof that this should be done at this (the cloudfront function) level (vs. on the Origin Request of lambda@edge for caching purposes). Best practices and all.

Thanks for the response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants