apache.htaccessmod-rewritehttp-redirect

Apache URL rewrite for 404 pages


We are moving web servers. However, all the content hasn't migrated yet. What I would like to do is whenever someone encounters a 404, I'd like to redirect them to the old server with the same path they were trying.

For example:

User visits: http://new.test.com/department/something.php

This would result in a 404, so I'd like to automatically send them here: http://old.test.com/department/something.php

Can I do this with a .htaccess file, or should I use PHP scripting on a custom 404 page on new.test.com to do the redirect?


Solution

  • You can use this rule in your DOCUMENT_ROOT/.htaccess file on the new site:

    RewriteEngine On
    
    # Request is on the new host
    RewriteCond %{HTTP_HOST} ^(www\.)?new\.test\.com$ [NC]
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    # Redirect to the old host URL
    RewriteRule . http://old.test.com%{REQUEST_URI} [L,NC,R]