Forum Moderators: coopster

Message Too Old, No Replies

Custom 404 redirect based on typed URL

404, PHP, redirect

         

galahad2

6:06 pm on Sep 16, 2009 (gmt 0)

10+ Year Member



Hi,

I need to set up a 404 error page in such a way that the URL typed by the user (for example aboutts.html instead of aboutus.html - or whatever mistyped URL it is) is checked against the entries in a database byt the 404 page.

If the database has an entry that matches the mistyped URL then the user gets forwarded to a different URL- not the 404 page but a different one.

If the database has no entry correspondiong to what was typed by the user, we just show the 404 page as normal.

Can this be done at all and if so, how would we go about it?

Thanks

rainborick

6:20 pm on Sep 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Spell checking has always seemed like black magic to me, so I don't have any coding suggestions. But have you tried Google's custom 404 page system? It wouldn't be nearly as seamless as the method you describe, but it works very well for providing URL matching suggestions.

galahad2

6:29 pm on Sep 16, 2009 (gmt 0)

10+ Year Member



Thanks, I will see if we can use that. The system I need to set up doesn't need to spell check at all really, it just needs to look to see if there's a matching entry in the database and then act accordingly- either redirect or just show the 404 page.

rocknbil

3:52 pm on Sep 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



First, if it's a 404 - be sure to output a 404 header, even with the "choice" page. Google and other sites have a problem with sites that don't appropriately output a 404.

I wouldn't do this with a redirect or a forward, I'd do it with a rewrite. With a rewrite, the address bar URL doesn't change and it's better for SE spiders.

It should be pretty simple, but it kind of depends on how you manage "friendly URL's" if you are doing that. A common approach is something like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /yourscript.php [L]

If the requested filename is not a file and it's not a directory, rewrite to yourscript.php. Inside yourscript.php, you take your input values and look up the items in the database. If you find (an) item(s), you output the page and a 200 is usually generated by the server (since it found yourscript.php.)

If no item is found, within your script you pass those values to a second function to look for alternatives/similar items. Output a 404 header, then the found item results. If no items are found, output your normal 404 page.

In either case, be very sure to output a 404 header if it gets to the second step.

The above scenario may be a single step for you if your pages aren't generated dynamically from a database, as in a shopping cart's products, for example.