Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to index.php of requested subfolder

I need to redirect to index.php of whichever directory is requested.

So I need:

http://www.site.com/folder/files/hello.php

To Redirect to:

http://www.site.com/folder/files/index.php

And also same for any subfolders:

http://www.site.com/folder/files/pages/other/hello.php

Redirect to:

http://www.site.com/folder/files/pages/other/index.php
like image 616
codingninja Avatar asked Feb 01 '26 00:02

codingninja


1 Answers

The (technically) right way

Construct a URI consisting of the current scheme (http / https / etc), hostname and path of the current file and issue a Location header.

$url = sprintf('%s://%s%s/index.php',
    $_SERVER['SERVER_PORT'] == 80 ? 'http' : 'https',
    $_SERVER['SERVER_NAME'], rtrim(dirname($_SERVER['PHP_SELF']), '/'))
header("Location: $url");
exit;

This is because a location header URI should be complete and absolute. Relative URIs are technically not allowed however there is a draft specification set to change this.

The pragmatic way

Just issue a relative Location header as it will most probably work.

header('Location: index.php');
exit;
like image 172
Phil Avatar answered Feb 02 '26 14:02

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!