4

So I have found these two questions:

Accessing original URL in IIS7 404 redirect page Get URL of page requested that caused a 404

but they are both in different languages. Is there any way to get the address that caused something like a 404 message to use in a custom message?

for example if I requested example.com/example1 and that page wasn't there and it redirected to my error page, how could I get example1 to display in a message like The pageexample1isn't there, or use that to create the page example1?

Community
  • 1
  • 1
FabianCook
  • 20,269
  • 16
  • 67
  • 115

2 Answers2

7

Since you are using PHP, you would be having access to the various PHP superglobals. $_SERVER['SCRIPT_NAME'], $_SERVER['REQUEST_URI'] etc can be used for the purpose. Something like this in the error page should do:

<?php
    printf("The page %s was not found.", $_SERVER['REQUEST_URI']);
?>

For more, do have a look at the $_SERVER superglobal documentation.

3

Can't it be in $_SERVER['HTTP_REFERER'] variable?

See http://php.net/manual/en/reserved.variables.server.php

Jan Tojnar
  • 5,306
  • 3
  • 29
  • 49
  • I have encountered the same problem,use referer is not always work,it depends,sometimes,all the server header values will lost,when redirect to error page. – xiaoyifang Dec 06 '13 at 01:37
  • @jan-tojnar These solutions don't work! If I ask for $_SERVER['HTTP_REFERER'] it is always blank and $_SERVER['REQUEST_URI'] gives the current script name not the error url. If a user types http://www.domain.com/nosuchfile.php and the .htaccess file points the 404 error as follows: ErrorDocument 404 http://www.domain.com/pagenotfound.php then $_SERVER['REQUEST_URI'] contains http://www.domain.com/pagenotfound.php – Chiwda Sep 07 '15 at 16:45
  • @Chiwda if you redirect to the error page, `REQUEST_URI` will of course contain the address of the error page. You can try using relative path in `ErrorDocument` directive, which won't cause redirect. – Jan Tojnar Sep 07 '15 at 20:35
  • OK. That seems to be working... ErrorDocument 404 /pagenotfound.php – Chiwda Sep 08 '15 at 15:17
  • does not work on my webserver referer is empty - possibly its a ajaxrequest... did not figure it out yet. – René W. Jul 02 '17 at 19:29
  • ok - maybe you have a look at $_SERVER['REDIRECT_URL'] if exist (might be depending on the installed server / configuration of "how" a error 404 is directed to the php-page.) – René W. Jul 02 '17 at 19:31