Keep referring URL after 404 page in php
===

I setup a 404 page and it works as it should. I am extracting the "error page" from the URL and using that to create a session since I need to pass it as a variable. My 404 has links to different pages and I would like to keep the referring url all the time even if the following pages exist. For example:

 1. www.mysite.com/100
 2. 100 does not exist and goes to my 404. The url is shown as step 1.
 3. Inside my 404 I have links to other pages likes www.mysite.com/link.php but I want that to be www.mysite.com/100/link.php

How can I accomplish this?

This is how I am passing the variable I need:

    $page2 = $_SERVER['REDIRECT_URL'];
    $str2 = substr($page2, 1);
    session_start();
    $_SESSION['DIST']=$str2;

Any help is appreciated!