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

Cut the .html from uri but remain querystring #7

Open
mrnonz opened this issue May 27, 2021 · 1 comment
Open

Cut the .html from uri but remain querystring #7

mrnonz opened this issue May 27, 2021 · 1 comment

Comments

@mrnonz
Copy link

mrnonz commented May 27, 2021

I have no idea how to remain querystring on the full url?

Here my now code

function handler(event) {
  var request = event.request;
  var uri = request.uri;

  // Check whether the URI is end with .html
  if (uri.includes(".html")) {
    var newUri = uri.replace(".html", ""); // Delete .html from URI

    var response = {
      statusCode: 302,
      statusDescription: "Found",
      headers: { "location": { "value": newUri } }
    };

    return response; // Redirect user to new location without .html
  }

  return request; // Pass normal request to CloudFront
}

Let's say client request with

https://abc.xyz/index.html?region=ap-southeast-1

, So I want to redirect client to

https://abc.xyz/index?region=ap-southeast-1

but when I testing with real CloudFront Functions I got this result instead.

https://abc.xyz/index

This missing my query param. How to solve this?

@mrnonz
Copy link
Author

mrnonz commented May 27, 2021

Solved with my solution.

I manual mapping into new url, but have another great idea for deal with this issue?

function objectToQueryString(obj) {
  var str = [];
  for (var param in obj)
    if (obj.hasOwnProperty(param)) {
      str.push(encodeURIComponent(param) + "=" + encodeURIComponent(obj[param]['value']));
    }
  return str.join("&");
}

function handler(event) {
  var request = event.request;
  var uri = request.uri;

  // Check whether the URI is end with .html
  if (uri.endsWith(".html")) {
    var newURI = uri.substring(0, uri.length - 5); // Delete .html from URI
    var redirectUrl = `https://${request.headers.host.value}${newURI}?${objectToQueryString(request.querystring)}`;

    var response = {
      statusCode: 302,
      statusDescription: "Found",
      headers: { "location": { "value": redirectUrl } }
    };

    return response; // Redirect user to new location without .html
  }

  return request; // Pass normal request to CloudFront
}

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

1 participant