StuffIKnowAboutComputersAndTheWeb > Htaccess

When redirecting one page to another, the page redirected *from* can be a relative URL but the page redirected *to* must be an absolute URL. For instance, the code used to redirect all requests from to is:

Redirect /index.html http://cleverbird.com/pwyky/

Note how the first URL is relative to the .htaccess file while the second is absolute and even includes the protocol.

This is not true if you're rewriting a URL, but it is true if you want to send a new header with a rewritten URL. So, for instance, to send a user to a new URL, change the address in the user's browser, and send an error 301 response, you would:

RewriteRule ^archives/(.*) http://juniorbird.com/archive/$1 [r=301,nc]

In the above example:

  • ^ designates the beginning of the file path, or everything after the domain name
  • (.*) designates the path to the page that the user has asked for. It could be anything! In fact the syntax .* translates to "any character [.] repeated any number of times [*]" We could also have used .+ (any character one or more times) or, if we had wanted to match just part of a string we could use .*?, which picks the shortest possible match thanks to the question mark at the end. We want to preserve and reuse this matched bit, so we book end it with parentheses.
  • $1 is whatever's in the first set of parentheses before the space
  • r=301 sends a 301 error code
  • nc means this is not a case-sensitive comparison

Before any RewriteRules in your .htaccess file, you need to have the lines:

Options +FollowSymlinks
RewriteEngine on

which turn the whole thing on.


This page last modified on September 05, 2005, at 11:53 AM

This work is licensed under a Creative Commons License

Recent Changes | Page History | Edit Page