Redirect non-www to www with Apache and NGINX

A two minute guide to redirecting all traffic on your website from the bare / naked / apex domain to www.

David Sugden
3 min readMar 21, 2021

It is a common requirement for system and website administrators to redirect users to a common entry point for their website — also known as a canonical hostname. This is usually in one of two directions, i.e. www to non-www or non-www to www.

This brief guide shows techniques for achieving the latter and we demonstrate how to achieve this using two common web servers, Apache and NGINX.

By “non-www” we refer to the “bare domain”, also known as the “naked domain” or “apex domain”; however, the same technique can be used for redirecting other source domains (e.g. to

301 Moved Permanently

Before we start, what is actually happening under the covers.

The HyperText Transfer Protocol (HTTP) 301 Moved Permanently redirect status response code indicates that the resource requested has been definitively moved to the URL given by the Location headers. A browser redirects to this page and search engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL).

— ref:

In summary, when a user visits your website they will receive a 301 response code along with the new location of your page.

You can test any site out using the Redirect Checker site.

Apache HTTPD logo

Apache HTTPD

There are a few techniques available to administrators of Apache web servers, and we’ll touch upon two of them here. The most common technique used will be via a .htaccess file, as this is most accessible to a wider group (for example, because not everyone can administer their web server directly).


The .htaccess file can be placed in the root directory (e.g. /var/www/html) or can be in…