URL redirection
URL redirection is arguably a MUST to have in your website's server configurations since it unifies URL addresses on the site and ensures, for SSL enabled connections, that it is loaded with https protocol. In some cases URL redirection can also be a guard against canonical issues in websites.
In this article we will look at how to force redirect URLs on a page to its www
and https
version in htaccess.
The code
The following code will force www and https on your site:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
What we do over here is this:
- First of all, we turn on the Apache's rewriting engine, via
RewriteEngine on
to make sure that our rewriting directives are applied. - Secondly, we check whether the hostname begins without
www
. If it does begin withoutwww
, then the rewrite condition in line 2 is met and thus a redirect response is sent back that points to the www version of the URL. TheL
flag effectively signals this rewrite rule as the last rule and thus ends the rewriting. - If the hostname does begin with
www
, then we have another check to perform — that ofhttps
. If the URL does not containhttps
, we send a redirect request for the URL withhttps
. Once again, theL
flag ends any further rewriting for the current phase.
And now you have a solid URL structure in place making sure all your user bases circulate around the https
and www
version of your site!