[英]Add trailing slash to url
I'm trying to add a trailing slash to urls using PHP. 我正在尝试使用PHP向URL添加尾部斜杠。 It can't be done with mod_rewrite since I have something similar to this in .htaccess:
因为我在.htaccess中有类似的东西,所以无法用mod_rewrite完成:
RewriteRule ^page/(.*)$ index.php?page=$1 [L]
and I want to validate that the page exists before 301 redirect with trailing slash. 我想验证页面是否存在于301重定向与斜杠之前。
Right now I'm using this code after validation: 现在我在验证后使用此代码:
if(substr($_GET['page'], -1) !== '/')
header('Location: http://example.com/'.$_GET['page'].'/'.$_SERVER['QUERY_STRING'],TRUE,301);
But is there any better approach? 但有没有更好的方法?
Simple way is that just remove the slash if available at the end of url and add it 简单的方法是只删除url末尾的斜杠并添加它
$str = "http://yoursite.com/testpage";
OR
$str = "http://yoursite.com/testpage/";
echo rtrim($str,"/").'/';
You already have the best solution for this. 您已经拥有了最佳解决方案。 I would just use
$_SERVER['REQUEST_URI']
instead of the already parsed $_GET['page']
and $_SERVER['QUERY_STRING']
: 我只使用
$_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;
}
Here is my universal solution, hope it helps for somebody: 这是我的通用解决方案,希望它有助于某人:
$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.