Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove trailing slashes in URLs with PHP

Tags:

php

I have some URLs, like www.amazon.com/, www.digg.com or www.microsoft.com/ and I want to remove the trailing slash, if it exists, so not just the last character. Is there a trim or rtrim for this?

like image 461
daniel Avatar asked Mar 06 '10 13:03

daniel


People also ask

How do you remove the slash at the end of a URL?

replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

How do you fix trailing slash issues?

A 301 redirect is the best way to resolve duplicate content issues caused by trailing slashes. If you're just fixing one page, you'd redirect the duplicate copy to the version that matches your chosen URL structure. Most trailing slash issues however, affect many pages across a website.

Does trailing slash matter in URL?

The trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent. But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs.

What is a trailing slash in URL?

Email Subscription. A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.


1 Answers

You put rtrim in your answer, why not just look it up?

$url = rtrim($url,"/"); 

As a side note, look up any PHP function by doing the following:

  • http://php.net/functionname
  • http://php.net/rtrim
  • http://php.net/trim

(rtrim stands for 'Right trim')

like image 169
Erik Avatar answered Oct 13 '22 22:10

Erik