Redirect www to Non-www and vice versa with Nginx

This tutorial will show you how to redirect a www URL to non-www, e.g. www.example.com to example.com, with Nginx. We will also show you how to redirect in the other direction, from a non-www URL to www.

Configure DNS Records

In order to set up the desired redirect, www.example.com to example.com or vice versa, you must have an A record for each name.

Option 1: Redirect www to non-www

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}
sudo systemctl restart nginx

Option 2: Redirect non-www to www

server {
    server_name example.com;
    return 301 $scheme://www.example.com$request_uri;
}
sudo systemctl restart nginx

How To Redirect www to non-www OR non-www to www with Apache

1. Configure DNS Records

In order to set up the desired redirect, www.example.com to example.com or vice versa, you must have an A record for each name.

2. Enable the mod_rewrite module

 a2enmod rewrite

3.1 Update site.conf or .htaccess file ( www to non-www)

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.yoursite.com 
RewriteRule (.*) http://yoursite.com/$1 [R=301,L]

3.2 Update site.conf or .htaccess file ( non-www to www)

RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com 
RewriteRule (.*) http://www.yoursite.com/$1 [R=301,L]

Example

<VirtualHost *:80>

ServerName example.net
Documentroot /var/www/html/

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.yoursite.com 
RewriteRule (.*) http://yoursite.com/$1 [R=301,L]

</VirtualHost>