5 Tips on Creating Redirects in htaccess

Per-directory rewrites need rewriting within <Directory> sections or .htaccess files, which introduces some complexity. However, if you only have permission to modify files, you must know how to put redirects in .htaccess files with RewriteRule.

RewriteEngine on
RewriteRule ^/index\.html$ /index.php [L]

A RewriteRule consists of three arguments separated by spaces.

The arguments are

  • Pattern: which incoming URLs should be affected by the rule, ex ^/index\.html$;
  • Substitution: where should the matching requests be sent, ex /index.php;
  • [flags]: options affecting the rewritten request, ex [L].

Here are 5 tips for creating redirects in .htaccess files.

1.Browser will cache 301 redirects

Browsers cache 301 redirects permanently unless cache directives in the HTTP response headers clearly state otherwise. The only method to erase these caches is to clear the browser cache, execute a hard reload, or disable caching entirely.

2.Handle special character in RewriteRule

Special characters like & and ? will be translated to their hexcode counterpart. The [NE] flag stops this from occurring.

RewriteRule ^/anchor/(.+) /bigpage.html#$1 [NE,R]

The above example redirects /anchor/xyz to /bigpage.html#xyz. If the [NE] is not present, the # will be transformed to its hexcode equivalent, %23 , resulting in a 404 Not Found error situation. Please keep in mind that the # symbol may only be used in a substitution, not in a pattern.

3.Handle non-alphanumeric characters in RewriteRule

In Apache 2.2, a B flag is introduced to escape non-alphanumeric characters before executing the transformation. And you should use non-alphanumeric characters directly in patterns rather than after url encode, ex using coleen's-story instead of coleen%27s-story .

4. Handle multiple lines RewriteRule in one .htaccess

The most specific should be at the top, and the least specific should be at the bottom. Also, make sure you're stopping processing with [L] after each redirect rule to prevent Apache from processing subsequent rewrite rules once it finds a match.

5. Handle space in RewriteRule

Using a \ before the space to escape it instead of %20 , ex.

RewriteRule ^county/phone\ number$ /front-door [R=301,L]

# Testing your htaccess rewrite rules

htaccess tester ♥ madewithlove
Easily test your htaccess rewrite rules
.htaccess Tester | TechnicalSEO.com
Test your .htaccess rewrite rules for HTTP redirects (server-side). This tool is leveraging the API developed by the madewithlove team.
Y Cheung

Y Cheung

Blogger, Programer & Traveler.