mod_rewrite in .htaccess

In the process of migrating the website I needed to catch old URLs and map them to the locations of the documents on the new website. Deploy a .htaccess file in the root of the website and introduce Redirect 301’s.

Simples…

Well for the static mappings yes.

e.g. 

Redirect 301 /2009/ /blog/

However to avoid having to implement lines for every single permutation mod_write allows to regex matching and re-writing.

Firstly it is neccessary to enable mod_rewrite which for me on Ubuntu means:

sudo a2enmod rewrite
sudo service apache2 restart

Don’t forget to insert ‘AllowOverride All’ in the '<Directory nn>' section. Then it is possible to add the following to the .htaccess file.

e.g. 

RewriteEngine on
RewriteRule ^20[01][0-9]/$ /blog/ [R=301]

In this case the important thing to remember is that the initial slash for the webpage is removed, so don’t match on ‘^/blah/$’ but instead ‘^blah/$’. This took a little while to figure out what was going on when I first implemented this. Also logging has changed since installed a web server from scratch, ‘RewriteLog’ has been depricated, you must now use ‘LogLevel alert rewrite:trace3’ or whichever level you require. Which can be applied to the '<Directory nn>' section.


More details can be found on the apache website:


© Mick Vaites 2018