htaccess: Redirecting different domains with different conditions

When developing large applications you face some issues or get some requirements, that you have to fulfill for your clients. Same as one of our white label client demanded non SSL website. Where our production environment is running on HTTPS and we are redirecting non SSL to SSL forcefully with .htaccess As below.

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

But as per requirement only one white label domain should run on HTTP only. This can be achieved by 2 methods.
Either we do conditional changes in our product OR we do changes in htaccess.
I choose second one.

Redirecting Multiple domains to same site only with htaccess

Following lines are to redirect specific domain (white label client’s domain) to HTTP only, and our production domain to HTTPS

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^whitelabelclientsdomain\.com$ [NC]
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} mainproductionurl\.com [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Redirecting WWW and non-WWW

Additionally, If you want to redirect www and non www domains try following code.

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.whitelabelclientsdomain\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^whitelabelclientsdomain\.com$ [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Please note that all the above code will work in your htaccess only if you have mod_rewrite module enabled in your apache.

Replace your domains accordingly.
Enjoy!!!

Shyam has written 29 articles

Shyam is senior full stack developer, who loves to explore new technologies and work on them. He's passionate about coding so can code 24/7. He uses PHP as a backend programming language.

He knows Laravel, MySQL, AngularJS, ReactJS, Redis, Kubernetes, Git, CodeIgniter, PHP, MVC pattern, Lodash, jQuery, VanilaJS, Teamcity and many other technologies and tools.

Shyam writes notes and hacks on his blog (https://shyammakwana.me). In spare time he can be found @ StackOverflow or crafting any new open source application.

Passionate Programmer and Meditator #PERIOD.