Direct all traffic to a single page using Apache rewrites

The .htaccess (hypertext access) file is a powerful WWW and FTP directory configuration file that can be used to modify connection requests to a server. It is a very useful tool in the web industry because it gives more options for web administration from the back end of the Apache servers (hence bypassing the cache for the redirected URL from search engines and databases). I wrote about removing the “www” from a URL using 301 redirects here. Today we will expand a bit on rewrite engine (RewriteEngine) using real examples.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.sanuja.com$ [NC]
RewriteRule ^(.*)$ http://sanuja.com/$1 [R=301,L]
RewriteRule .*\.(jpg|jpeg|gif|png|bmp)$ http://sanuja.com [R,NC]
redirectMatch 301 ^/blog/abc/ https://sanuja.com/blog/123/

The rewrite engine(in Python and C# engine is defined as modules or libraries) must be called-in using the code, RewriteEngine On, before you can use any of the available functions. Usually the only time one would turn off an engine is, if and only if, a process (or several processes) conflict with each other. While it is not uncommon to use more than one all in for a engine, usually it is discouraged to do so.

Second, you have to understand the codes for calling in built in libraries. It is easy to find them since there are many reference books and Internet repositories with information on these functions. In the above code, lines 2 to 4 using rewrite library functions; Cond and Rule, while the last line is using the 301 redirect library function; Match. Since I already discussed the www redirection in a previous post (read above), today we will learn how to redirect (or divert) all requests to a folder, rather than a single file.

The reason why folder redirect is very useful; it allows a wide range of address to be redirected to a single address and it allows redirection of unknown requests (404 for example) to a much more meaningful page. This is where the redirectMatch can take over all requests to a folder (all files) and redirect it to a single URL. For example, in the above code, ^/blog/abc/ indicate that anything with /blog/abc/ get redirected. The second part of the code defines where to be redirected; in this particular example it is https://sanuja.com/blog/123/.