aws-samples / amazon-cloudfront-functions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

URL redirect/rewrite

kiransharma24d opened this issue · comments

finding a way to successfully do a URL redirect/rewrite so that your base URL does not change and the query string should be rewritten with another query string. We are planning to away from my website hosted on NGINX, which is currently where these redirect/rewrites are happening.

For example, try to run www.gopetplan.com/aapo it will redirect to www.gopetplan.com/partners/AAPO by serving static webpage(which is hosted on 3rd party vendor) without changing base URL, though static webpage content getting served from another domain

Would something like this work for your use case?

function handler(event) {

    var request = event.request;
    var uri = request.uri;
    var host = request.headers.host.value;
    
    if(!uri.includes('/partners/')){
        uri = uri.toUpperCase()
    
        var response = {
            statusCode: 302,
            statusDescription: 'Found',
            headers:
                { "location": { "value": `https://${host}/partners${uri}` } }
        }
        return response;
    }
    
    return request;
}

This function takes the URI path (/aapo) and checks if it does not contain /partner/. If not, the function will :

  1. Make the URI path uppercase (/AAPO). Not sure if this is required, but it was upper case in your example.
  2. Issue a 302 redirect to the new URL using the same host header as the base host for the URL and adds the /partner/ to the URI path.

If the URI path contains /partner/ the function will return the URL as is (no-op).