从PHP重定向重写URL

时间:2014-10-17 20:15:54

标签: php url rewrite

如何重写此网址:

http://localhost/?=register

看起来像这样?:

http://localhost/index.php/Register

2 个答案:

答案 0 :(得分:0)

您的重定向代码:

header('Location: /index.php/Register/',true,302);
exit;

要访问/ Register /值,请使用:

$_SERVER['PATH_INFO']

答案 1 :(得分:0)

使用header命令执行重定向后,您必须记住编写代码来处理该URL。

/index.php/Register会尝试在“/index.php/”文件夹中加载“注册”文件... 404错误

因此,您需要使用apache modrewrite将这些“虚拟文件夹”重定向到可以处理它的集中式脚本。

.htaccess上有这样的事情:

RewriteEngine on

RewriteRule ^index.php/(.*)$    index.php

然后,在你的index.php中,你会将incomming URL视为检测到该文件,并随意做任何事情。

我通常使用catch-all(将所有内容重定向到/index.php)然后中断URL并对其进行处理,因此我可以拥有任意数量的虚拟文件夹/文件。这是我自己的处理任何传入请求的函数:

function extractUri($uri="") { 
    if ($uri == "") $uri = isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != "" ? $_SERVER['REQUEST_URI'] : "";
    if ($uri != "") {
        # removes query from request
        if ($uri[0] != "/") $uri = "/".$uri; # ALWAYS START WITH /
        $uri = explode("?",$uri);
        $uri = str_replace("..",".",array_shift($uri)); # little exploit remover
        $uri = explode("/",str_replace("//","/",$uri));
    } else
        $uri = array("/");

    $context = array();
    foreach ($uri as $part)
        array_push($context,preg_replace("/(\.){2,}/","\.",$part)); # prevents ..

    $action = array_pop($context); # file (with extension)
    $original_action = $action; # preserve the original file with extension (I work w/o them)
    $ext = "";
    if ($action == "") $action = 'index'; # so if you are accessing folder/, then you probably want the index
    else if (strpos($action,".")!==false) { # remove extension
        $action = explode(".",$action);
        $ext = array_pop($action);
        $action = implode(".",$action);
        $action = removeSimbols($action,true,false); # makes sure it is a valid filename, this function removes any weird character
    }
    return array($context,$action,$original_action,$ext); # returns the folder structure (array), the page/action, the page/action with extension, and said extension (lots of repetition to speed up later)
}

所以extractUri(“/ index.php / Register”)会返回:

Array ([0] => "/", [1] => "index.php"), "Register", "Register", ""