Forum Moderators: coopster & phranque

Message Too Old, No Replies

404 handler script

looking to redirect 404's to root of current dir

         

Slud

5:03 pm on Oct 2, 2002 (gmt 0)

10+ Year Member



I'm looking for a "solution" to redirect 404's to the root of the current directory.

Example:
/brand/discountinued-model.htm -> /brand/

Does anyone have a favorite Perl script for doing this? Would it be possible with a clever Redirect line in my .htaccess (don't have mod_rewrite installed at my host)?

jatar_k

5:05 pm on Oct 2, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I don't see why your custom 404 couldn't be set to a script that parses through the url and then sends them to the root of the subcategory they are in.

Slud

5:13 pm on Oct 2, 2002 (gmt 0)

10+ Year Member



That's exactly what I'm looking for. I don't code Perl, but I'm fairly handy at modifying existing code. If you could suggestion any existing script which accomplishes similar, I'd be very grateful.

jatar_k

5:16 pm on Oct 2, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I would try hotscripts.com, I could figure a php one but I am not as proficient in perl.

Slud

5:21 pm on Oct 2, 2002 (gmt 0)

10+ Year Member



Thanks, I'll pick through there and cgi-resources.com

amoore

5:39 pm on Oct 2, 2002 (gmt 0)

10+ Year Member



I think something like this would work for you:

#!/usr/local/bin/perl -w
use strict;

print "Status: 301\n";
if ( $ENV{'REQUEST_URI'} =~ /(.*)\/[^\/]+$/ ) {
print "Location: $1\n\n";
} else {
print "Location: /\n\n";
}

Let me comment on that for you a bit:

#!/usr/local/bin/perl -w
use strict;
# that stuff should go at the top of every perl script.

print "Status: 301\n"; # change the 404 status to a redirect (302 if you like)
if ( $ENV{'REQUEST_URI'} =~ /(.*)\/[^\/]+$/ ) {
# match everything up to the last "/" in the requested URL.
print "Location: $1\n\n";
# send the redirect to one level up.
} else {
# if the match thing above failed, just send them to the root.
# you could return a 404 here or send them to a real page or something.
print "Location: /\n\n";
}

make this script something like "/cgi-bin/htredirect.cgi" and then make a .htaccess that looks like this:
ErrorDocument 404 /cgi-bin/htredirect.cgi

Slud

6:06 pm on Oct 2, 2002 (gmt 0)

10+ Year Member



Thanks amoore. That's right on the money. That regexp is exactly what I needed. I may have to add some exceptions for specific url's, but the code you included get's me 90% there.