Redirects with mod_rewrite
Overview
A redirect automatically changes the browser’s URL from one address to another. Different redirect codes can be used to control how the browser or search engine spider interprets the redirect. In this guide, we'll cover how to set up redirects using mod_rewrite
in the .htaccess
file.
Usage
All redirects are configured within the .htaccess
file located in the document root of your target domain or subdomain. Below is a simple example that redirects www.example.com
to example.com
:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ http://example.com/$1 [R,L]
To reverse the process and redirect example.com
to www.example.com
, you only need to slightly modify the RewriteCond
and RewriteRule
:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R,L]
How It Works
- RewriteCond: Stands for "rewrite condition." This directive checks if the specified condition is met.
- RewriteRule: Stands for "rewrite rule." If the condition is met, this rule is applied to the current URL, using regular expression substitution.
The mod_rewrite
module uses Perl-compatible regular expressions (PCRE) to match and manipulate URLs.
Required Components
For a redirect to function correctly, two key components must be included:
- RewriteEngine On: Enables the URL rewriting engine.
- RewriteBase /: Anchors all rules to the current directory. This directive is crucial when working with addon domains and subdomains.
These lines are essential, though they are omitted in the following examples for brevity.
Examples
Redirect to SSL
The following example redirects all HTTP traffic to HTTPS:
RewriteCond %{HTTPS} !^on$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]
Explanation:
- The server checks for the
HTTPS
environment variable. If SSL is not active (!^on$
), it assumes the request is using HTTP. - The
RewriteRule
then redirects the request to the same hostname and URL path but using HTTPS.
Redirect Codes
You can specify a redirect code by appending a number to the R
flag in the RewriteRule
. By default, a 302 Found
redirect is used, but you can change this by specifying one of the following codes:
Code | Name | Description |
---|---|---|
301 | Moved Permanently | Resource is no longer accessible under the original URL; use the new URL |
302 | Found | URL is temporarily under a new resource; continue using the original URL |
303 | See Other | Response resides elsewhere and should be retrieved using a GET request |
307 | Temporary Redirect | URL temporarily resides elsewhere; use the original URL in future requests |
308 | Permanent Redirect | Similar to 301 but preserves the request method (e.g., POST); experimental |
See Also
By following these guidelines, you can effectively manage URL redirects using mod_rewrite
in your .htaccess
file, ensuring smooth transitions and better control over your website's URLs.