如果不存在并且用户被重定向到404错误页面,如何在Apache / PHP中获取实际请求URL?

问题描述:

I want to fetch the actual URL of the request made by the client, how do I do that? I mean if someone requests a page that does not exists, like, http://localhost/invalid.php, and I have set 404 custom error file to http://localhost/test.php, then how do I get to know what was the actual URL requested by the user.

I have tried this in IIS7. I have set the Custom Error Page to /test.php, and whenever the user requests a URL which does not exist, I could still access that URL using $_SERVER['REQUEST_URI'] in /test.php and the URL in browsers still remains the same.

But I am having problem doing the same in Apache. I have set the Custom Error Page to /test.php but when user requests a page which doesn't exist, the user is redirected to a /test.php and I cant access the actual URL which the user requested. I've tried this print_r($_SERVER) but did not find the actual request URL any where in the $_SERVER array.

我想获取客户端发出的请求的实际URL,我该怎么做? 我的意思是如果有人请求一个不存在的页面,比如 http://localhost/invalid.php code>,我已经将404自定义错误文件设置为 http:// localhost / test .php code>,那么我如何才能知道用户请求的实际URL是什么。 p>

我在IIS7中尝试了这个。 我已将自定义错误页面设置为/test.php,每当用户请求不存在的URL时,我仍然可以使用/test.php中的$ _SERVER ['REQUEST_URI']和浏览器中的URL访问该URL 保持不变。 p>

但我在Apache中遇到同样的问题。 我已将自定义错误页面设置为/test.php,但是当用户请求不存在的页面时,用户被重定向到/test.php,我无法访问用户请求的实际URL。 我试过这个 print_r($ _ SERVER) code>但是在 $ _ SERVER code>数组中找不到实际的请求URL。 p> div>

I believe you could do it by using a RewriteCond rather that an error 404.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ test.php?errpath=$1

The first line checks if the file actually exists.
The second routes the client to test.php.

Then in test.php you put something like:

<?php
    if ($_GET['errpath'] == "" || $_GET['errpath'] == "/") {
        require("index.php");
    }
    else {
        echo "The url ".$_GET['errpath']." does not exist.";
    }
?>

That checks if errpath is nothing or just a forward slash (meaning the client would normally be showed index.php), and is so, requires it. Otherwise do whatever you want for the 404 error page.

P.S. Sorry if the explanations seem patronizing, I just hate it when people tell me to do something and I don't understand. I don't want to do that to anyone else.