重定向至请求的子文件夹的索引.php


Redirect to index.php of requested subfolder

我需要重定向到请求的任何目录index.php

所以我需要:

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

重定向至:

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

对于任何子文件夹也是如此:

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

重定向至:

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

技术上)正确的方式

构造一个由当前方案(http/https/等)、主机名和当前文件的路径组成的URI,并发出位置标头。

$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;

这是因为位置标头 URI 应该是完整且绝对的。从技术上讲,不允许使用相对 URI,但是有一个草案规范集来更改这一点。

务实的方式

只需发布一个相对位置标头,因为它很可能会起作用。

header('Location: index.php');
exit;

这可以在.htaccess本身中完成,因此不需要任何PHP代码。

通过httpd.conf启用mod_rewrite.htaccess,然后将以下代码放入DOCUMENT_ROOT/.htaccess文件中:

RewriteEngine On
RewriteBase /
RewriteRule (.+?)/[^./]+'.php$ /$1/index.php [L,NC]

若要将folder/files/hello.php重定向到folder/files/index.php请在folder/files/hello.php文件中使用以下行。

<?php
$URL =  'http://'.$_SERVER['SERVER_NAME'].'/folder/files/index.php';
header("Location:  $URL ");
?>

对下一次重定向使用类似的语法。