Question: 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?

Answer: 
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,"/").'/';

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

```