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.
- Enable
mod_rewrite: The rewrite module must be active in your Apache server configuration. On many Linux systems, this can be done via the command line usingsudo a2enmod rewritefollowed by a server restart. - Allow Override: Apache needs permission to read
instructions from local configuration files. In your main Apache
configuration file (usually
httpd.conforapache2.conf), the directory block for your website must have theAllowOverride Alldirective set, which enables the use of.htaccessfiles.
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]- Pattern: A regular expression that Apache matches against the requested URL path.
- Substitution: The target URL or internal path where the request should be sent if the pattern matches.
- Flags: Actions enclosed in square brackets that
tell Apache how to handle the rule, such as
[R=301]for a permanent redirect or[L]to stop processing subsequent rules.
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):
- Create or open the
.htaccessfile in your website’s root folder. - Add the
RewriteEngine Ondirective to activate the runtime rewriting engine. - 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.