Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
user422039 Avatar asked Feb 20 '11 07:02

user422039


1 Answers

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,"/").'/';
like image 143
Bunty Avatar answered Oct 20 '22 01:10

Bunty