http to https and www to non www

.htaccess redirects http ⇆ https and www ⇆ non-www

The expanding adoption of HTTPS as the default connection protocol for sites has acquainted a couple of new difficulties with developers and system admins. For an example, the need to solidify a canonical domain by redirecting HTTP websites to HTTPS. Also this tutorial help you to setup redirecting from www to non-www or non-www to www.

This is useful way to avoid content duplication on search engines, optimize user experience and some security issues as well.web security

You can configure 301 (moved permanently) redirects adding one of following redirect rule, either to the Apache config file (virtual host) if you have access to it. Or you can simply add it to the .htaccess in the root directory of your website. First you should select the correct code snippet which appropriate for your situation. There are no changes need to be done to following codes. Make sure rewrite module of your server is enabled.

www with https

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</IfModule>

non-www with https

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</IfModule>

www with http

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteRule ^.*$ http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</IfModule>

non-www with http

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</IfModule>

Using following tool you can easily check the redirect rules are correct. www.redirect-checker.org

Share Now

1 Comment Posted

Leave a Reply

Your email address will not be published.


*