/ devops

Setting up redirects using Apache

Setting up redirect URL's are quite a common use case especially when site maintenance and upgrading is going on. As part of a complete migration, setting up a permanent redirection (301) makes more sense, especially from SEO perspective.

Recently, I migrated from Wordpress to Ghost and realized the default URL generation strategy for the 2 CMSs were different and a permanent redirection makes sense. If you are looking for more information on How I migrated from Wordpress to Ghost, check out here.

Here's how I did setup permanent redirects (301) from my Wordpress URLs to Ghost URLs. Make sure you have mod_rewrite enabled. To do so, use the following

a2enmod rewrite

With the module enabled, it's time to write the rewrite rules for the specific redirects we are interested in. Here's an example.

 nano /etc/apache2/conf/sample.conf
 RewriteEngine on
 RewriteRule "/blog/category/this-is-a-test/" "/blog/2017/12/test/" [R=301,L,NE]

The above rules enable the rewrite engine and set a rewrite rule for the URL /blog/category/this-is-a-test/ to /blog/2017/12/test/. The [] segment setup the flags for the rewrite rule. The important flag is the R=301 which instructs Apache to send a redirect 301 status back to the browser. A R=302 would rather instruct a temporary redirect.

The flag NE instructs the Apache to not replace the special characters with the respective hex code. The flag L instructs Apache to stop processing any further rules in the sequence and processes the request.

More details on the Apache flags can be found here.

Don't forget the restart the Apache service to bring the configuration changes to effect.

/etc/init.d/apache restart
Love Hasija

Love Hasija

Full Stack Research Engineer, Software Architect | Helped build next generation software systems | Distributed Systems Fanatic | Open Source Hacker.

Read More
Setting up redirects using Apache
Share this