Redirect from www. To Your Root Domain

Redirect your visitors to your root domain from the www subdomain.

Redirecting is useful for a variety of situations, including redirecting a visitor that goes to your domain with www. prefixing the URL to your domain without that prefix.

Now provides configuration to help make redirecting easier through the routes property within a now.json file.

To redirect visitors from the www. subdomain to your naked domain, you can create a now.json file with the aforementioned configuration property in a new folder to deploy as a separate deployment to the one that is aliased to your naked domain.

Step 1: Project Setup

First, create a directory for this project to live in. For example, using a Unix terminal, create the directory redirect and cd into it:

mkdir redirect && cd redirect

Next, create a now.json file in that directory with the following content:

{
  "version": 2,
  "alias": ["www.your-domain.com"],
  "routes": [
    {
      "src": "/(.*)",
      "status": 301,
      "headers": { "Location": "https://your-domain.com/$1" }
    }
  ]
}

A now.json configuration file that redirects all paths to the naked domain.

Configuration Breakdown

The above configuration uses a few properties to configure the deployment:

With this configuration, you are allowing Now to understand how to route the visitor with the routes property from the source, comprising of a PCRE regex capture group /(.*), a HTTP status of 301 (Moved Permanently), and a Location header that directs to the naked domain with the captured path appended via $1.

Step 2: Deploying

With the configuration complete and ready, you are ready to deploy. If you have not yet installed Now, you can do so by installing the Now Desktop app which installs Now CLI automatically, or by installing Now CLI directly.

Using Now CLI, you can deploy the project from your terminal using the following command:

now

To push your deployment into production, deploy and alias it with the production aliasing target:

now --target production

Now, when visiting either the production alias (www.your-domain.com), a staging alias, or a deployment URL, the visitor will get redirected to the location set as defined by the routes property in the now.json file.



Written By
Written by timothytimothy
on January 23rd 2019