Forum Moderators: phranque

Message Too Old, No Replies

.htaccess 301 recursive redirect

         

ryno267

9:36 pm on Oct 10, 2007 (gmt 0)

10+ Year Member



I got a 404 reporter that emails me any 404 hits to our site and I've been getting 404s on some really old directories that were supposed to be not scanned by bots because I had a robots.txt setup but, whatever the bots got it and now they keep hitting it and I don't want SE's to index those directories.

I want to redirect any request for //domain.com/dir/* to just reroute to my main //domain.com with a 301 for the SE's. I want it recursive as there are hits for random subdirectories in there and random files, too many to single out and put into the htaccess.

So far I have this:


# no-www please
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

# 301 Permanent Redirects
Redirect 301 /dir http://example.com/

Now that takes for example a request for //domain.com/dir and redirects it fine... BUT.. if at request for //example.com/dir/subdir or //example.com/dir/file.jpg comes in... it sends it to //example.com/subdir or //example.com/file.jpg and then 404's again... so it's just removing /dir/

...with that said.... help please :)

[edited by: jdMorgan at 10:55 pm (utc) on Oct. 10, 2007]
[edit reason] example.com [/edit]

jdMorgan

10:51 pm on Oct 10, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use mod_rewrite for both, and put the most-specific rule first to avoid stacked redirects:

# Redirect "dir/*" to "/"
RewriteRule ^dir/ http://example.com/ [R=301,L]
#
# no-www please
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]

This is not "recursion." This is simply a wild-card pattern (because there is no end-anchor on the "^dir/" pattern). Recursion refers to a procedure which invokes (or can invoke) itself, or the act of that procedure invoking itself.

What tripped you up is the prefix-matching of the Redirect directive; Any part of the URL-path not matched by the specified URL-path prefix in a Redirect directive is appended to the substitution URL. Mod_rewrite uses regular expressions, and behaves differently, in that back-references must be explicitly created and invoked.

Jim

[edited by: jdMorgan at 10:54 pm (utc) on Oct. 10, 2007]

ryno267

11:16 pm on Oct 10, 2007 (gmt 0)

10+ Year Member



Ah.. got it...

Well thank you very much... works as intended!

Chuck