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

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

```