---
title: "Redirects with mod_rewrite"
date: "2016-01-23"
category: "web-content"
slug: "redirects-mod-rewrite"
---

## Overview

A redirect changes the URL in the browser from one address to another. Different redirect status codes instruct browsers and search engine crawlers how to handle the response.

All redirects are controlled through a [[htaccess-guide]] file in the [[where-is-site-content-served-from]] of your target [[creating-addon-domain]] or [[creating-subdomain]].

## Basic Usage

The following example redirects `www.example.com` to `example.com`:

```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ http://example.com/$1 [R,L]
```

The reverse -- redirecting `example.com` to `www.example.com` -- requires only a minor change to the `RewriteCond` and `RewriteRule`:

```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R,L]
```

`RewriteCond` defines a condition to match, and `RewriteRule` defines the substitution to apply using [Perl-compatible regular expressions (PCRE)](https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions). If the condition matches, the rule is applied to the current URL.

## Required Components

Every redirect requires these two lines:

```
RewriteEngine On
RewriteBase /
```

`RewriteEngine On` enables URL rewriting. `RewriteBase /` anchors all rules to the current directory. **`RewriteBase` is essential when working with addon domains and subdomains.**

The following examples omit these two lines for brevity.

### Example: Redirect to SSL

```
RewriteCond %{HTTPS} !^on$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]
```

This checks the `HTTPS` environment variable. If SSL is not active, it redirects to the HTTPS version of the same URL, preserving the hostname (`%{HTTP_HOST}`) and path (`$1`).

## Redirect Codes

An optional status code can be added to the `R` flag using the format `R=XXX`. The default is 302. Available codes:

| Code | Name | Description |
|------|------|-------------|
| 301 | Moved Permanently | Resource has permanently moved. Use the new URL going forward. |
| 302 | Found | Resource temporarily resides at a different URL. Continue using the original URL. |
| 303 | See Other | Response is elsewhere and should be retrieved with GET. Commonly used after POST requests. |
| 307 | Temporary Redirect | Resource temporarily resides elsewhere. Continue using the original URL. |
| 308 | Permanent Redirect | Similar to 301 but preserves the HTTP method. [Experimental](https://tools.ietf.org/html/rfc7238). |

## See Also

- [Introduction to Regular Expressions and mod\_rewrite](http://httpd.apache.org/docs/current/rewrite/intro.html) (httpd.apache.org)
- [URL Rewriting with mod\_rewrite](http://httpd.apache.org/docs/current/rewrite/) (httpd.apache.org)
