How to Create a Basic Apache URL Rewrite Rule?

This article provides a straightforward guide on how to set up a basic URL rewrite rule using Apache’s mod_rewrite module. You will learn the essential prerequisites, the core syntax of a rewrite rule, and a practical step-by-step example to redirect user traffic seamlessly. Whether you want to create cleaner URLs for SEO or redirect old links to new pages, mastering the basics of Apache rewriting is a fundamental skill for web administrators.

Prerequisites for Apache URL Rewriting

Before writing any rules, you must ensure that Apache is configured to allow URL manipulation. This requires enabling the rewrite module and configuring your directory permissions.

The Structure of a Rewrite Rule

Apache URL rewriting is primarily handled using two directives: RewriteCond (optional test conditions) and RewriteRule (the actual transformation). A basic rule follows a specific three-part syntax:

RewriteRule Pattern Substitution [Flags]

Step-by-Step Implementation Example

The most common way to implement a basic rewrite rule without altering main server configuration files is by using an .htaccess file located in your website’s root directory.

Follow these steps to redirect a request from an old page (about-us.html) to a new page (about.html):

  1. Create or open the .htaccess file in your website’s root folder.
  2. Add the RewriteEngine On directive to activate the runtime rewriting engine.
  3. Write the rewrite rule specifying the old path and the new path.
RewriteEngine On
RewriteRule ^about-us\.html$ about.html [R=301,L]

In this example, ^about-us\.html$ acts as the pattern matching the exact URL. The about.html is the substitution target. The R=301 flag tells browsers and search engines that the page has moved permanently, and the L flag ensures no further rules are processed if this one matches.