简体   繁体   中英

Add trailing slash to url

I'm trying to add a trailing slash to urls using PHP. It can't be done with mod_rewrite since I have something similar to this in .htaccess:

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

and I want to validate that the page exists before 301 redirect with trailing slash.

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

$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'] :

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM