Web Redirect via .htaccess

In our Web Redirect via AWS Route 53 article, we’ve talked about how to redirect a domain name to another website. In this article, we’ll talk about how to use different types of Apache directives within a .htaccess file to redirect traffic within the same website or from one website to another website. 

About .htaccess

Using .htaccess for web redirection is an aged approach. It’s like everyone have started to drive electronic cars but we still have our old petrol car in our garage. One day we put some petrol in it and found it still works very fine. Similarly, while the world are progressing to PaaS and SaaS, this IaaS technology still works very fine too. So we decide to create this article as a dedicated “garage” for our .htaccess driven web redirection method.

Different from the web redirect via AWS Route 53, the prerequisite of using .htaccess file for redirection is to have a web hosting account (where the web server runs Apache). In other words, we need to have a hosting space where we can store the .htaccess file. Then by editing the content of the .htaccess file, we can instruct the web server to redirect the web traffic to the destination. The destination can be either a different URL within the website itself, or another website, as shown below.

In the IaaS world, when we have an Apache HTTP server as our web server, we can use the main configure file (i.e. http.conf) to store our directive configuration settings. But sometimes we don’t have permission to access this main configure file, like in a “one server multiple websites” situation. In this case, we can use the .htaccess file to override the central configuration settings for a particular directory. So .htaccess is also known as “distributed configuration file”.

Given it’s a directory-based configuration file, we can put it in various directories. The most common place is under our website’s root directory. But for certain reasons if we need to put two .htaccess files into two directories, e.g. one in a parent folder and one in its child folder, keep in mind that the .htaccess file under the child folder will override the one in the parent folder.

There are many directives that we can configure in the .htaccess file. However, not all Apache directives are permitted. The quickest way to find whether a particular directive is permitted in a .htaccess file is to check the Context attribute on that directive’s reference page. If “.htaccess” is listed under the Context line as shown below, it means we can use this directive in the .htaccess file.

In this article, we are focusing on the web redirect related directives, i.e. the directives under mod_alias and mod_rewrite. If you are interested in other Apaches directives, the details are available at its Directive Index.

Hands On

To configure the .htaccess file of a website, we’ll need to get access to the web hosting directory first. The access channel may vary based depends on hosting providers. Usually we can access the directory via SFTP or command line interface. Assume we want to configure .htaccess to redirect HTTP to HTTPS and we want to access the file via a SFTP client application. The steps are like below:

1. Launch the SFTP client application, and then enter the server address and login credentials.

2. Once connected, locate the .htaccess file from the web file directory. If there is an existing .htaccess file, follow 3a onwards; if no existing .htaccess found, follow 3b onwards

3a. Download the .htaccess file, and open it in a text/code editor
4a. Add the following code after the
” RewriteBase / ” line


RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

5a. Save the changes
6a. Upload the .htaccess file back to the same directory

3b. Create a new text file in a text/code editor
4b. Copy and paste the following code in the text file


RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

5a. Save the text file and name it temp.txt file
6a. Upload the file to the document root, e.g. the public_html folder, and rename it to .htaccess

The steps for different connection channels may vary, but in a nutshell the “adding the configuration code” part is the same.

Apache loads .htaccess file(s) upon every document request. So once we uploaded the updated .htaccess file, the redirection change should take effect immediately.

Note that .htaccess file is a text file and it’s also a server configuration file. It means a typo in this text file may cause the website malfunction. So it’s highly recommended to do a backup of the website before updating the .htaccess file. And after updating the .htaccess file, check the website thoroughly to make sure it functions as expected.

Reference

In addition to the redirection example used above, there are a number of other redirection scenarios. We’ve grouped the configuration code by mod_alias and mod_rewrite below.

mod_alias Directives

Under Apache module mod_alias, the Redirect and RedirectMatch directives are common ones used for web redirect. The scenarios and mapping code examples are as below:

Redirect within the same website

#Redirect website A's entire site to a subfolder
Redirect 301 "/"   "http://www.websiteA.com/subfolder/"

#Redirect website A's subfolder X to subfolder Y
Redirect 301 "/subfolderX"   "/subfolderY"

#Redirect website A's page 1 to page 2
Redirect 301 "/subfolderX/page1.html"   "/subfolderY/page2.html"

#Redirect website A's txt files to html files
RedirectMatch 301 "(.*)\.txt$"   "$1.html"

#Reuse URL parameters in the redirection 
RedirectMatch 301 "/page1.php?id=(.*)&tag=(.*)$"   "/$1/$2"

Redirect to another website

#Redirect website A's entire site website B
Redirect 301 "/"   "http://www.websiteB.com/"

#Redirect website A's subfolder X to website B's subfolder Y
Redirect 301 "/subfolderX"   "http://www.websiteB.com/subfolderY"

#Redirect website A's txt files to website B's html files
RedirectMatch 301 "(.*)\.txt$"   "http://www.websiteB.com/$1.html"

Note that the quotation marks are optional unless there is a space enclosed in any part of the URLs. And “301” represents a permanent redirect. We can replace it with “302” (representing a temporary redirect) or other 3xx HTTP status codes. For more information, see Status Code Definitions – Redirection 3xx.

mod_rewrite Directives

Comparing with the mod_alias directives, mod_rewrite directives provide a more flexible and powerful way for web redirections. For example, it supports unlimited rules and each rule can have unlimited rule conditions. The scenarios and mapping code examples in this module are listed below.

Note that it’s a prerequisite to have the RewriteEngine enabled when using mod_rewrite directives. If the code below can’t be found in the .htaccess file, we’ll need to add it above the rewrite code blocks first.

#Enable RewriteEngine
RewriteEngine on

Redirect within the same website

#Redirect website A's subfolder X to subfolder Y
RewriteRule "^/subfolderX/?$"   "/subfolderY/" [R=301,L]

#Automatically load website A's subfolder X 
RewriteRule "^$"   "/subfolderX/" [L]

#Redirect website A's shortened path to the full path 
RewriteRule "^(.*)/fn/(.*)$"   "$1/full-name/$2" [L,R=301]

#Redirect website A's xxx.html to page.php?id=xxx 
RewriteRule "^([a-zA-Z-]*).html" "/page.php?id=$1" [QSA,L]

#Remove www from all website A's URLs
RewriteCond "%{HTTP_HOST}"   "^www\.websiteA\.com$" [NC]
RewriteRule "(.*)"   "https://websiteA.com/$1" [R=301,L]

#Add www to all website A's URLs
RewriteCond "%{HTTP_HOST}"   "^websiteA\.com$" [NC]
RewriteRule "(.*)"   "https://www.websiteA.com/$1" [R=301,L]

#Rewrite website A's homepage according to the User-Agent
RewriteCond  "%{HTTP_USER_AGENT}"  "(iPhone|Android)"
RewriteRule  "^/$"   "/index-for-mobile.html"  [L]

RewriteRule  "^/$"   "/index-for-standard.html"     [L]

#Redirect access from non-existing pages to the index page
RewriteCond "%{REQUEST_FILENAME}"   "!-f "
RewriteCond "%{REQUEST_FILENAME}"   "!-d"
RewriteRule "."   "/index.php" [L]

Redirect to another website

#Redirect website A's entire site to website B retaining the same path
RewriteRule "(.*)"   "http://www.websiteB.com/$1" [R=301,L]

#Redirect website A's entire site website B's homepage
RewriteRule "(.*)"   "http://www.websiteB.com/" [R=301,L]

#Redirect website A with a subfolder X to website B 
#without the subfolder X but retain the query string
RewriteCond "%{REQUEST_URI}"   "^/subfolderX/(.*)$"
RewriteRule "^(.*)"   "http://www.websiteB/%1" [R=301,NC]

#Redirect website A's search query to Google
RewriteCond "%{REQUEST_URI}"   "/search/(.*)" [NC]
RewriteRule "(.*)"   "http://www.google.com/search?q=$1" [R,NC,L]

Summary

Using .htaccess file on the directory basis provides flexibility, but it also brings up the performance and security concerns. Before setting up the .htaccess file, it’s recommended to read through Apache’s When (not) to use .htaccess files to understand the potential impacts first.

You May Also Like

About the Author: Richard Zhao

My name is Richard Zhao. I'm a solution architect and owner of cloudstudio.com.au. Having built knowledge bases for many companies, I'd like to use this cloud studio to share knowledge and ideas with wider people on the internet.

Leave a Reply

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