I needed a simple way of redirecting all requests from an old website to the new location, but the user should be made aware that the URL has changed and that he should update his bookmarks.

The solution has two parts:

  1. a mod_rewrite rule that stores the old url in a variable and then calls an information page
  2. the information page itself, displaying the new url and redirecting to the new location after a few seconds

mod_rewrite rule to redirect to a new location

This rule goes into the Apache httpd main configuration file httpd.conf or in the virtual hosts configuration file. The RewriteRule selects the full URL and stores it in the variable $1. It then redirects the user to a new url redirect.php (but still on the same old system). The old URL is placed in the variable originalUrl where it will be picked up by the PHP script.

The RewriteCond is required, otherwise the redirect.php page itself would also be redirected, which would cause an infinite loop.

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/redirect.php
RewriteRule ^(.*) /redirect.php?oldUrl=$1 [R=301,L]

PHP redirect script

The PHP script below retrieves the old URL and creates the new URL from it. In this case the new URL looks pretty much like the old URL, just at a different domain, so the code generating the new URL is trivial. But one can also add more complex code here.

It then writes a <meta http-equiv='refresh'> tag in the header which sends the browser to the new website. The new URL and the delay is defined by the content=... parameter.

Following that comes some information text so the user is informed that the link has been changed and what the new link is.

To define the new URL and the delay, edit the values for $newUrl and $delay near the top of the file.

<html>
<header>

<?
$newUrl='https://my.new.website.com/some/location' . $_GET['oldUrl'];
$delay=5;
print "<meta http-equiv='refresh' content='$delay;url=$newUrl'>";
?>

</header>
<body style="font-family:Helvetica,Arial,sans-serif; margin-left:80px;margin-top:80px">
<h2>The URL for this application has changed</h2>
The new URL is :
<br>
<br>

<? print "<a href='$newUrl'>$newUrl</a>" ?>

<br>
<br>
Please update your bookmarks.
<br>
You will be automatically forwarded in <? print $delay ?> seconds, or just click on the link.
<br>
<br>

<h2>Die URL dieser Anwendung hat sich ge&auml;ndert</h2>
Die neue URL lautet :
<br>
<br>

<? print "<a href='$newUrl'>$newUrl</a>" ?>

<br>
<br>
Bitte aktualisieren Sie Ihre Bookmarks.
<br>
Sie werden automatisch in <? print $delay ?> Sekunden weitergeleitet, oder klicken Sie einfach auf den Link.
</body>
</html>