Apache
  Home arrow Apache arrow Custom Error 404 Documents with PHP
IBM Rational Software Development Conference
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Download TestComplete 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
eWeek
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
APACHE

Custom Error 404 Documents with PHP
By: Eric 'phpfreak' Rosebrock
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 14
    2003-04-11

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    This article will help developers who wish to create a new web site layout. Once you have read this, you will be able to redirect users to the new pages created via a 404 error page. Read more.

    Have you ever designed your website, built the structure and decided one day that you want to completely redesign your layout? Well, if you have an established website, changing your structure can be a real pain for your users or people searching for your site in search engines. This tutorial will show you how to avoid getting those Error 404 Not Found errors and redirect people back into your new design.

    Let's say that we have a few files such as this:

    Your Site Root
      /index.php
      /page1.php
      /page2.php
      /page3.php

    Your new layout schema that you decided to use will change to this:

    Your Site Root
      /index.php
      /articles.php (Was page1.php)
      /images.php (Was page2.php)
      /guestbook.php (Was page3.php)

    We will assume that you are going to remove the old files after you do your site design. When your site was running before you had about 10 websites linking to your pages and you had submitted everything to search engines. When people click on your old links, they'll get an Error 404 / Document Not Found error message. Let's avoid getting that message and direct the users to your index to avoid any traffic loss.

    Utilizing Apache's built in custom error document handling you can setup your own error 404 document that redirects the user to your index page and gives them a message as well as displays your index page. The first thing we need to do is build our error handler. I use a php script that includes my index.php file, gives the user a message at the top and the re-directs them to the main page after 2 seconds. Here's how:

    <?php
    //errror404.php
    echo "<font color="#FFFF00" size="3"><center><strong>You have reached a page that has changed or no longer exists.
          You have been redirected to our index page. Please update your bookmarks!</strong></center></font>";
    //Meta refresh to send them back to index.php
    echo "<meta http-equiv="refresh" content="2;URL=/index.php">";
    //include the index.php so that we can give them something to look at besides an ugly error
    include 'index.php';
    ?>

    There you have it! A simple php script that gives you a good looking Error 404 page and redirects the user to your index page. On the next page, we'll show you how to setup a htaccess file that allows Apache to use this new error404.php script.

    The next step requires you to either have administrative access to your Apache web server's configuration files or send an email to your admin and ask them to allow overrides for your website. A directive should be added to your httpd.conf for the directory which your website lives in. Let's say for this example it's /www/htdocs. Here's a line in your httpd.conf that you must have for this .htaccess file to work:

    <Directory /www/htdocs/yoursite>
         AllowOverride FileInfo
    </Directory>

    Once you have that done, you'll need to create a file called ".htaccess" and place it inside your website's directory. Here's how simple this .htaccess file is:

    ErrorDocument 404 /error404.php

    Wow that was simple eh? After you have completed all of the above steps, you can now test it out. Let's call up http://www.yourdomain.com/foo.php (Where foo.php is a file that does not exist). You should be directed to your index page and see a message that appears at the top of the screen for approximately 2 seconds and then the user will be directed back to your index.php file.

    Congratulations, You've successfully redirected all broken links on your website back to your index! You will no longer lose traffic due to random clean-ups of your files and site changes. Just don't delete the error404.php because that would be too ironic that you can't even display your own error document!

    Here's a few more custom error documents that you can make for your website. Just use the same methods above that we used for creating these new pages. If you were really cool, you could setup a switch inside your error404.php file and manage all of your custom errors in one file. Here's the list:

    Error in Client
    400 Bad syntax
    401 Unauthorized
    402 Not Used (Payment Granted)
    403 Forbidden
    404 Not Found

    Error in Server
    500 Internal Error
    501 Not Implemented
    502 Overloaded
    503 Gateway Timeout

    More information can be found at the Apache Webserver page: http://httpd.apache.org/docs/custom-error.html


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Apache Articles
    More By Eric 'phpfreak' Rosebrock

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! Did you say mainframe? e-kit

    Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise.
    FREE! Go There Now!


    NEW! Hello World: Learn how to install and use the Rational Asset Manager Eclipse client

    In this tutorial, you can learn how to install and configure the IBM Rational Asset Manager Eclipse client, explore the different views in the Asset Management perspective, learn various search techniques, work with existing assets, and submit a new asset.
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    NEW! Trial download: IBM Informix Dynamic Server Express Edition V11.0

    Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Manual Tester V7.0.1

    Try the latest version of IBM Rational Manual Tester V7.0.1 by downloading a free trial from IBM developerWorks. This manual test authoring and execution tool promotes test step reuse to reduce the impact of software change on testers and business analysts and addresses the needs of teams performing at least a portion of their testing manually.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for People

    Visit IBM developerWorks to try the IBM SOA Sandbox for people. The SOA Sandbox for people provides a trial environment with the necessary tooling and components required to enable consistent human and process interaction and collaboration, showing how you can improve user experience and business productivity.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    APACHE ARTICLES

    - Programmatically Manipulating Microsoft Exce...
    - Installing PHP under Windows
    - Compressing Web Content with mod_gzip and mo...
    - Compressing Web Output Using mod_deflate and...
    - Setting Up Apache 2.0.45 to Parse PHP Pages
    - Custom Error 404 Documents with PHP
    - Using Apache and PHP on Mac OS X
    - ASP: Active Sessions, Active Logins and Tota...
    - Working With Oracle on Windows: Part 1
    - The Quick-n-Dirty Guide to Setting Up Apache...
    - Installing Apache With SSL: The Complete Gui...
    - 7 Powerful .htaccess Customization Tips
    - Trap And Get Notified: A Practical Solution ...
    - One Way To Use Server Side Includes
    - Using ForceType For Nicer Page URLs


     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway