Redirect rules for VirtualHosts

The most efficient way to redirect your site is to create the proper redirection rules in the correct hierarchy.

HTTP to HTTPS redirection

First thing I like to do is to create a redirect for non-https requests. So my default VirtualHost configuration for port 80 looks like this. It only gets here when an unsecured http request is made:

<VirtualHost _default_:80>
DocumentRoot "/opt/bitnami/apache2/htdocs"
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]
...

This simply redirects everything to https.

IP to domain redirection

But we want to have a couple of other redirects in place. What about your IP address? I don’t want my site to be accessible in any other way than through my domain. The following redirect rule forwards my IP to my domain:

<VirtualHost _default_:443>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^111\.222\.333\.444
  RewriteRule (.*)  https://www.domain.com$1 [R=301,L]
...

So, if a request is being made with my IP address, it will be redirected to my domain.

Non-WWW to WWW redirection

Finally, I want my site to be accessible from the www only, therefor I redirect all non-www requests to the same request including www. Here’s the exact rewrite rule that should be added to the VirtualHost configuration for port 443:

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

Conclusion

it’s not that difficult. And there will be no additional redirects in place than the minimum needed to make your site work properly.