0

I using below PHP & htacess codes for routing structure in my project, I would like to add forced trailing slash to all routes like that;

localhost/project/about-us > localhost/project/about-us/

It's working on main path like localhost/project/ so I cannot display main path without trailing slash like localhost/project because it's redirect me(that's what I want for all routes).

How can I do that? Thanks. Codes:

function request_path()
{
    $request_uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
    $script_name = explode('/', trim($_SERVER['SCRIPT_NAME'], '/'));
    $parts = array_diff_assoc($request_uri, $script_name);
    if (empty($parts))
    {
        return '/';
    }
    $path = implode('/', $parts);
    if (($position = strpos($path, '?')) !== FALSE)
    {
        $path = substr($path, 0, $position);
    }
    return $path;
}

$routes = [
  '/' => function()
  {
      echo 'home';
  },
  'about-us' => function()
  {
      echo 'about';
  },
  'profile/edit' => function()
  {
      echo 'profile edit';
  }
];

$path = request_path();

if (isset($routes[$path]) AND is_callable($routes[$path]))
{
  $routes[$path]();
}
else
{
  echo 404;
}
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
User9123
  • 47
  • 6
  • `project` is an actually existing folder, in which the project resides? Then that trailing slash redirect is done by the `DirectorySlash` directive, which is part of mod_dir. But that does not apply, if what you are requesting does not point to a physically existing folder in the first place - so you will have to do this yourself. You can either do this from within PHP, or directly in your .htaccess. (For the latter, please do a bit of research, because this isn’t exactly a new question.) – CBroe Nov 09 '20 at 12:52
  • thanks for the response @CBroe, project is a real folder but others are route as you can see, I just want to redirect routes to has trailing slashes. – User9123 Nov 09 '20 at 13:03
  • https://stackoverflow.com/a/21417551/1427878 explains the basics of doing this via .htaccess; if you want to do it in PHP instead - then check if the requested URL ended with a slash, and if not, add it and use `header` with `Location: …` to redirect from there. – CBroe Nov 09 '20 at 14:22
  • Does this answer your question? [Htaccess: add/remove trailing slash from URL](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url) – MrWhite Nov 12 '20 at 14:19

0 Answers0