RewriteCond and RewriteRule tricks for .htaccess

The Apache web server has a module called “mod_rewrite”. It allows for redirecting and modifying the requested URL. Below are some of the most popular modifications and redirects that can be executed. Put these commands in a  “.htaccess” file in the document root of the web site. In order of popularity:

#1. Redirect everything the www subdomain

With or without “www”? Not such a hard question considering that you can answer on both and redirect one. This snippet, which can be combined with the previous one, redirects all non-www requests to the www subdomain:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{HTTP_HOST} !^www\. [NC]
 RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Having your website on the “www” subdomain may be beneficial when dealing with CDN or security services.

#2. Redirect everything to HTTPS

There is hardly any reason not to run your website over SSL (HTTPS). Also it is very important that you answer to both HTTP and HTTPS. This snippet redirects all non-HTTPS traffic to HTTPS:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{HTTPS} !on [NC]
 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

It is important to choose one true (canonical) URL for SEO reasons.

#3. PHP file to handle all non-static requests

Also known as the front controller pattern. This mechanism is the basis for any web framework. In PHP it allows you to read the actual requested path in the $_SERVER[‘REQUEST_URI’] global variable. The rewrite looks like this:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php [QSA,L]

Note that the PHP file is bypassed for existing files (static content).

#4. Rewrite GET parameter to URL part

If you have an URL that you should be calling with “GET /orders?id=13” and you want it to respond as if “GET /orders/13” was called, then you may use the following:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_URI} ^/orders [NC]
 RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC]
 RewriteRule ^(.*)$ %{REQUEST_URI}/%1\? [R,L]

This is especially useful when migrating URL schemes and need legacy support. Note how the escaped question mark at the end of the “RewriteRule” removes the GET parameter(s).


One thought on “RewriteCond and RewriteRule tricks for .htaccess”

  1. I used the SSL rewrite code listed above, added to my .htaccess file and works like a charm. Thanks for being so straightforward and easy to use!

Leave a Reply

Your email address will not be published. Required fields are marked *