Error404 redirect to specific folder depending on current page?

Joined
12 Feb 2006
Posts
17,310
Location
Surrey
is it possible to redirect a user to index.php of the current folder if they go to a page that doesn't exist?

e.g. if they visit xyz.com/service-one/london.php, they get the page for london as this page exists, but if they visit /service-one/kingston.php (which doesn't exist) it redirects to /service-one/index.php

and then /service-two/kingston.php would redirect to /service-two/index.php

Thanks
 
Associate
Joined
29 Sep 2005
Posts
818
Location
St Neots / Dublin
Which webserver? In nginx this appears to work for me:
Code:
location ~ ^/(?<dir>.*)/(?<page>[^/]+\.php)$ {
  try_files /$dir/$page /$dir/index.php =404;
  include fastcgi_params;
}

edit: An alternative that works for any server might me to use the "Front Controller Pattern" to redirect all requests to a specific PHP file, then do your logic in PHP - check if the page exists, if so include() it, otherwise replace the filename on the URL string, check if that exists.

In nginx: try_files $uri $uri/ /index.php?q=$uri&$args;
Then in PHP you can use $_REQUEST["q"] to check the path and load the right PHP file.
 
Soldato
Joined
3 Jun 2005
Posts
3,117
Location
The South
You could do it through htaccess setting up a 404 error page using ErrorDocument with an absolute path (top two lines) or URL (bottom line) to your "index.php" -
Code:
Alias "/service-two" "/mycpaneldir/public_html/service-two"
ErrorDocument 404 /service-two/index.php

ErrorDocument 404 https://mydomain.com/service-two/index.php


* Worth noting i'm not entirely sure if this would be an issue with SEO/SEM/crawlers unless your "index.php" throws a 404 header response.
 
Back
Top Bottom