[英]Add trailing slash to url
我正在嘗試使用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);
但有沒有更好的方法?
簡單的方法是只刪除url末尾的斜杠並添加它
$str = "http://yoursite.com/testpage";
OR
$str = "http://yoursite.com/testpage/";
echo rtrim($str,"/").'/';
您已經擁有了最佳解決方案。 我只使用$_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;
}
這是我的通用解決方案,希望它有助於某人:
$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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.