Tutorial: How to Redirect Traffic from One Domain to Another Using Google Cloud Functions

Introduction

Whether you are rebranding, moving to a new domain, or consolidating your content, redirecting traffic from one domain to another is a frequent requirement. In this tutorial, we will guide you on achieving this using Google Cloud Functions and a code example that is highly configurable to your needs. Additionally, Cloud Functions are pay-per-use and have a free tier that is enough for most customer needs ‘All customers get 2 million monthly invocations free, not charged against your credits.‘.

By the end of this tutorial, you will be able to deploy this code to Google Cloud with the configuration that you require – setting the target URL, and deciding whether to forward the source path and query parameters.

Prerequisites

Before we get started, ensure that you have the following:

  • A Google Cloud account.
  • Basic understanding of Node.js and JavaScript.

Steps to Redirect Traffic Using Google Cloud Functions

Step 1: Setting Up Your Google Cloud Function

First, we want to create a new Google Cloud Function in the Cloud Console. So now you need to go to the Cloud Console and navigate to Cloud Functions.

Finding the cloud functions in the Google Cloud Panel

Enable the APIs that are required.

Enabling the required APIs for Cloud Functions

Click ‘Create Function’.

Creating the Cloud Function

Provide a name for your function.

Make sure you select ‘2nd gen’ as the environment.

Also, make sure you select ‘us-cental1’ as the location.

Choose HTTPS as the trigger and check ‘Allow unauthenticated invocations’.

Step 2: Environment Variables Configuration

In the ‘Environment Variables’ section, set the following variables:

  • REDIRECT_CODE: This is the HTTP status code that will be sent back to the client to indicate the redirection. Commonly used values are ‘301’ (Moved Permanently) or ‘302’ (Found).
  • TARGET_URL: This is the URL where you want to redirect the traffic.
  • FORWARD_PATH: If set to ‘true’, the source URL path will be appended to the TARGET_URL. If ‘false’, only the root TARGET_URL will be used.
  • FORWARD_QUERY: If set to ‘true’, any query parameters in the original URL will be forwarded to the TARGET_URL.

Below is an example of a config if we want to redirect our https://old-domain.com to https://google.com with the path (/contact) and query parameters (?utm_source=xyz) of the user request also forwarded.

Assigning variables to the cloud function

Step 3: Write Your Cloud Function

After you click ‘Next’ at the bottom, you will be taken to the source code section. In the ‘Code’ section, set the runtime to Node.js, and paste the following code into index.js.

const functions = require('@google-cloud/functions-framework');
const url = require('url');

functions.http('helloHttp', (req, res) => {
  const targetUrl = url.parse(process.env.TARGET_URL, true);
  const redirectCode = parseInt(process.env.REDIRECT_CODE);
  const shouldForwardPath = process.env.FORWARD_PATH === 'true';
  const shouldForwardQuery = process.env.FORWARD_QUERY === 'true';

  if (shouldForwardPath) {
      targetUrl.pathname += req.path;
  }

  if (shouldForwardQuery && Object.keys(req.query).length > 0) {
      targetUrl.query = {...req.query, ...targetUrl.query};
  }

  // remove old 'search' property which can conflict with 'query'
  targetUrl.search = null;

  const redirectUrl = url.format(targetUrl);

  res.redirect(redirectCode, redirectUrl);
});

This function retrieves the environment variables, constructs the redirect URL based on the path and query parameters (if needed), and then uses the res.redirect function to perform the redirection.

This version of the code also merges together the query parameters of the incoming request and the query parameters of the targetUrl.

Pasting the code in the cloud function creation UI

Step 4: Deploy Your Function

Once the function and environment variables are set, click ‘Deploy’ to make your function live. Google Cloud will provide you with a URL for your function once the deployment is complete. You can then use that function to test whether all of your config is correct.

Now that you’ve created and deployed your Cloud Function, you may want to map a custom domain to it. This is beneficial as it provides a cleaner and more professional-looking URL for your users.

Actually, you probably searched for this solution since you already had a specific domain that you wanted to redirect. ๐Ÿ™‚

Step 5: Mapping a Custom Domain to Your Cloud Function

To map a custom domain to a Google Cloud Function, you’ll need to use a service such as Firebase Hosting or Google Cloud Run. Here’s how you can do it using Google Cloud Run as it is easier than the Firebase option:

Just go to ‘Cloud Run’ using the search in the header.

Finding Cloud Run using search

From the top menu, select ‘Manage custom domains’ and click on ‘Add mapping’.

List of existing Cloud Run services

Select the cloud function we just created before. You probably only have only one function there, but you can figure it out by the name that you gave it before.

Creating a custom domain mapping for the cloud function

You then need to verify the domain via Google Search Console. Here is a good tutorial on how you can do that.

Custom domain mapping is pending

Once the ownership has successfully been verified, then you can go back to the Google Cloud Platform and continue with the custom domain mapping.

Domain ownership verified in Google Search Console

Once the domain is validated and you click on ‘Continue’, then you need to configure the A and AAAA records at your domain registrar that are shown in the dialog. You probably want to configure the ‘www’ version of the mapping to the same cloud function.

Finalising the custom domain mapping

When the records have been successfully validated then at some point your custom domain will be mapped to the function and a secure HTTPS connection available for the users. Note that due to the way Cloud Run checks for the DNS entries, it might take up to 24 hours to correctly work.

Conclusion

Congratulations! You’ve successfully set up a serverless function to redirect traffic from one domain to another using Google Cloud Functions. You can now easily manage your redirection rules by adjusting the environment variables. We hope this tutorial has been informative and helpful.

How can I do it without writing code?

If you are looking for an easy way to redirect a domain and not have to configure all of the technical infrastructure for it, then you should consider using the Domain Forward service. You can sign up using the link below and create your first redirect using the Getting Started guide.

administrator