Skip to content

Instantly share code, notes, and snippets.

@miooochi
Last active January 26, 2024 12:13
Show Gist options
  • Save miooochi/9d1e92fae2c762f0cb36fcbeb5200c8d to your computer and use it in GitHub Desktop.
Save miooochi/9d1e92fae2c762f0cb36fcbeb5200c8d to your computer and use it in GitHub Desktop.
A JavaScript program for a 301 redirect with path mapping, suitable for deployment as a Cloud Function on AWS

Proposal

exports.handler = async (event) => {
  const request = event.Records[0].cf.request;
  const requestUri = request.uri;

  // Path mapping logic:
  const pathMappings = {
    "/": "/featuretoggle/uk", // Redirect root path to /featuretoggle/uk
    "/old-path": "/new-path", // Add more path mappings as needed
  };

  const targetUri = pathMappings[requestUri] || requestUri; // Redirect to mapped path if present, otherwise use original path

  if (targetUri !== requestUri) {
    const response = {
      status: '301',
      statusDescription: 'Moved Permanently',
      headers: {
        'location': [{
          key: 'Location',
          value: targetUri,
        }],
      },
    };
    return response;
  } else {
    return request; // Pass through request without modification if no redirect needed
  }
};

Key points:

  • Path Mappings: Customize the pathMappings object to define your specific URL redirection rules.
  • 301 Status Code: The 301 status code signals a permanent redirect to search engines and browsers.
  • Location Header: The Location header specifies the target URL for the redirect.
  • Pass-through: If no path mapping matches, the request is passed through without modification.

Remember:

  • Deploy this code as a Cloud Function on AWS.
  • Configure CloudFront to trigger the Cloud Function for appropriate events (e.g., viewer request).
  • Test thoroughly to ensure redirects work as expected.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment