How to setup 301 redirects using .htaccess

May 13, 2023

Background

We recently launched a website for a client. The website was a redesign of an existing website. The previous website had some hardcoded links, therefore after the launch there was a requirement to setup 301 redirects for hardcoded links on the old website to new links on the new website.After banging my head around for some time, I couldn’t get the redirects working so if you are stuck doing what I wanted to do and if your requirements are similar to mine, read on.

Assumptions

I used .htaccess file to setup the redirects and assume the following –1. Your web server is Apache.2. You have write access to the .htaccess file on your server.3. You want to redirect an individual link to a new link.It is a good practice to backup the .htaccess file before modifying it in case you need to roll it back.

Requirements

1. The old website was built using asp and the new website used Drupal.2. The domain remained same with the redesign.3. The hardcoded links on the old website were of the following format –

· http://www.someurl.com.au/index.asp (needed to be redirected to http://www.someurl.com.au on the new website)

· http://www.someurl.com.au/contact_us.asp (needed to be redirected to http://www.someurl.com.au/contact-us)

how to loss fat

4. So the redirects had to be setup so that –

· /index.asp would redirect to /

· /contact_us.asp would redirect to /contact-us

and so on (there were about 20 such links).

Approach that worked

I tried a few options in .htaccess and none of them worked including the following -redirect 301 /index.asp http://www.someurl.com.auBut what worked was the following –RewriteRule ^index.asp http://www.someurl.com.au [R=301,L]RewriteRule ^contact_us.asp http://www.someurl.com.au/contact-us [R=301,L]The above has to be added after the following -

 RewriteEngine onRewriteBase /index.php

# Custom URL redirects hereand before the following -

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_URI} !=/favicon.icoRewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Hope the above helps someone stuck setting the 301 redirects.