Hire a senior Perl / Python programmer today; download my up-to-date resume (PDF)
John Bokma MexIT
freelance Perl programmer

A permanent redirect using RedirectMatch

Friday, August 18, 2006 | 1 comment

Today Denise posted a question regarding using a permanent redirect from one part of her site on an Apache web server, to another part of her site for all files to the Usenet group alt.internet.search-engines:

Can't quite figure this out, so thought I'd ask one of the 301 gurus here ~

What is the proper way to redirect all the pages in a particular
subdirectory to the homepage using a 301 without doing a 301 for each page

For instance, every page in
http://www.example.com/something/ would redirect to http://www.example.com
(where one would find a note that the /something/ part of the site
unfortunately no longer exists).

I tried this:

RedirectPermanent /something/ http://www.example.com/

and it works perfectly when someone types in
http://www.example.com/something - it redirects to http://www.example.com

But when someone goes to
http://www.example.com/something/particularpage.html it redirects to
www.example.com/particularpage.html when I want it just to redirect to

I know I can do a separate 301 for each page in the /something/ directory -
but that would take a lot of time & space, so I'm hoping there's a more
elegant solution.

Sure there's something elementary I'm missing - hoping someone can set me


From the above message it was clear that she was using the Apache HTTP server so I replied with the following solution (excerpt):

Anyway (untested):

RedirectMatch permanent /something/.* http://www.example.com/

See: http://httpd.apache.org/docs/1.3/mod/mod_alias.html#redirectmatch

The directive RedirectMatch, provided by the mod_alias module of the Apache web server, can take either 2 or 3 parameters:

 RedirectMatch [status] regex URL

The status is optional and defaults to temporary (302). Since Denise wanted a permanent redirect, also known as 301 redirect since that's the corresponding status code, I specified "permanent".

The second parameter (when status is given, otherwise it's the first) consists of a regular expression. Since she wants everything that starts with /something to go to a different URL I used /something/.*, which matches /something/ followed by zero or more characters. This seems to miss out /something but I assumed that /something would redirect to /something/. The latter is matched by the given regular expression and hence the permanent redirect does take place.

And indeed this permanent redirect solution did work because shortly after Denise replied to my Usenet post with the message that "It works perfectly!".

RedirectMatch related

Please post a comment | read 1 comment by Jeremy L. Gaddis | RSS feed
Books and optimal line length >
< Mind the antidepressant sales pitch