Redirect site from www to non-www

It is better to make web site available with one URL. Many sites work with both wwww and non-www (naked domain) urls.

Using www or non-www is personal choice. One advantage of using wwww for URL is when you have lot of sub domains. If you use non-www url, cookies set by the domain will be available to sub domains. This will increase bandwidth usage as cookie need to be sent with every request browser make to web server.

Apache

If you are using Apache web server, you can redirect wwww to non-www url by adding following code in .htaccess file

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ https://yourdomain.com/$1 [L,R=301]

Redirect non-www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [L,R=301]

Nginx

If you use Nginx, it is better create a server entry for www URL, then set a redirect

server {
    server_name www.yourdomain.com;
    return 301 $scheme://yourdomain.com$request_uri;
}

If you want to use same server entry for www and non-www, add following code to nginx server entry for the web site.

Redirect www domain to non-www

if ( $host != 'yourdomain.com' ) {
    return 301 https://yourdomain.com$request_uri;
}

If you use custom ports, use

if ( $host != 'yourdomain.com' ) {
    return 301 https://yourdomain.com:$server_port$request_uri;
}

Redirect Naked Domain to www

if ( $host != 'www.serverok.in' ) {
    return 301 https://serverok.in$request_uri;
}

Related Posts

Redirect

htaccess

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *