301 (Permanent) redirection using .htaccess file

301 redirection with .htaccessA few days back one of my project’s domain changed. The nature of this project was such that it provides URLs to it’s subscribers to use in their site for different purposes. As it has a huge user base, it was quite impossible to change the URLs already provided to the subscribers. That’s why I searched for a solution which will redirect the subscribers to new domain. I knew HTACCESS files can provide this type of service. So, I searched web for a solution to this problem – 301 redirection with HTACCESS file. Then I found the following solution. Before I provide the solution, I just want to say I am not an expert of HTACCESS 🙂 .

I have created .htaccess file with the following line to redirect any request to http://www.oldurl.com/ to https://www.newurl.com/.

redirect 301 / https://www.newurl.com/

The line stated above tells Apache server to redirect all request to http://www.oldurl.com/ will be redirected to https://www.newurl.com/using 301 permanent redirection. It worked fine.

After implementing the solution I faced another problem. The line of code was redirecting to only HTTPS irrespective of the request made to HTTP or HTTPS. This caused a problem for the pages which were non-secured, I mean shown via HTTP. These pages contain elements like CSS, JavaScript files, images etc. which are linked as HTTP. So, browsers started generating security warnings. Again I took help of Google and searched for a solution. After studying different problems I wrote the following lines of code in the .htaccess file and it worked.

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://www.newurl.com/$1 [L,R=301]
RewriteCond %{HTTPS} !^443
RewriteRule ^(.*)$ http://www.newurl.com/$1 [L,R=301]

The above code does a conditional redirection. If the request is made to HTTP then it redirects to HTTP and the same is for HTTPS.

FYI, my project is built with CodeIgniter and the redirection worked fine with it.

Share
blog