Categories: Snippets

Redirect non-www to www and HTTP to HTTPS using htaccess

Below snippet shows how to redirect a site from non-www to www (or viceversa) and from HTTP to HTTPS. To be more clear, the configuration will redirect the following host names:

http://onlinenote.in

https://onlinenote.in

to

https://www.onlinenote.in

I’ll also show a small change to redirect the www to the non-www version, if you prefer the non-www.

To configure the redirects, add the following redirect rule either to the Apache config file if you have access to it, or to the .htaccess in the root of your site:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

If instead of www.onlinenote.in you want the default URL to be onlinenote.in, then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
Share

Recent Posts

How to remove .html, .php, etc (extension) from URL?

To remove the .html extension from your urls, you can use the following code in…

5 years ago

.htaccess file useful snippets

If you get 404 page not found error after installation. In this case your server…

6 years ago

Redirect non-www to www in .htaccess

Below snippet shows how to redirect a site from non-www to www [crayon-66390ecab435b780013819/] or [crayon-66390ecab4360082803787/]…

6 years ago

Common .htaccess file Redirects

Below shows common redirects using htaccess file. [crayon-66390ecab450d815897008/] The CI .htaccess shouldn't be in the…

6 years ago