简体   繁体   中英

Removing trailing slash from URL using PHP

What I need:

example.com/webpage/ should redirect to example.com/webpage

I am using:

$path = $_SERVER['REQUEST_URI'];
if(substr($path, -1) == '/')
{
    $path=rtrim( $path, '/\\' );
    header("Location: $path");
}

The problem:

When someone requests the homepage (with or without trailing slash), the value of $path becomes '/' and it causes a loop. Can anyone offer me a better solution?

Try

$path = $_SERVER['REQUEST_URI'];
$path = preg_replace('#/\s*$#', '', $path);
header("Location: $path");

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