向网址添加尾部斜杠

时间:2011-02-20 07:53:51

标签: php mod-rewrite

我正在尝试使用PHP向URL添加尾部斜杠。因为我在.htaccess中有类似的内容,所以无法用mod_rewrite完成:

RewriteRule ^page/(.*)$ index.php?page=$1 [L]

我希望验证页面是否在301重定向之前存在,并带有斜杠。

现在我在验证后使用此代码:

if(substr($_GET['page'], -1) !== '/')
  header('Location: http://example.com/'.$_GET['page'].'/'.$_SERVER['QUERY_STRING'],TRUE,301);

但是有更好的方法吗?

3 个答案:

答案 0 :(得分:9)

简单的方法是只删除url末尾的斜杠并添加它

$str = "http://yoursite.com/testpage"; 

OR 

$str = "http://yoursite.com/testpage/";


echo rtrim($str,"/").'/';

答案 1 :(得分:3)

您已经拥有了最佳解决方案。我只想使用$_SERVER['REQUEST_URI']代替已经解析过的$_GET['page']$_SERVER['QUERY_STRING']

if (substr($_GET['page'], -1) !== '/') {
    $parts = explode('?', $_SERVER['REQUEST_URI'], 2);
    $uri = 'http://example.com'.$parts[0].'/'.(isset($parts[1]) ? '?'.$parts[1] : '');
    header('Location: '.$uri, true, 301);
    exit;
}

答案 2 :(得分:0)

这是我的通用解决方案,希望对您有所帮助:

 $site_adress = (((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
$whole_url = $site_adress . $_SERVER['REQUEST_URI'];


$pos = strpos($whole_url, "?");
$changed_url = FALSE;
if($pos !== FALSE && $whole_url[$pos - 1] != "/") {
    $whole_url = substr_replace($whole_url, "/", $pos, 0);
    $changed_url = TRUE;
} else if($pos == FALSE && substr($whole_url, -1) != '/') {
    $whole_url = $whole_url . "/";
    $changed_url = TRUE;
}
if($changed_url) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: " . $whole_url);
    exit();
}