$routes->redirect doesn't work inside of conditional statement

I’m trying to avoid using htaccess for this particular work and I wish to make a redirect from trailing-slash to non-trailing slash URLs, but only if the URL is does not contain only “/novo/”, something like:

https://www.example.com/novo/example-uri/ —> https://www.example.com/novo/example-uri

I’ve tried to code and test it, but the results are none, nothing actually happens about the URL or route, but dd() works just fine, behaving as intented (removing the trailing slash).

The code below is in routes.php aside of other redirects and right before multiple $routes->connect(), all contained Router::scope('/', ...) {...}.

if (
        substr(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), -1, 1) === '/' &&
        parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) !== '/novo/'
    ) {
            parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),
            substr(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 0, -1),
            ['status' => 301]

If I add the dd(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), substr(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 0, -1)); right before or after the redirect, it works dumping the correct URLs that should be redirected in the $routes method.

Also tried using header(), but ended up with other problems.

What can I do about it? Is the routes.php not capable of having conditionals like this? What’s the best alternative to solve this problem besides htaccess?

I think a better approach would be using a middleware Middleware - 4.x

1 Like

I ended up using htaccess, but gonna study more about using the middleware.

1 Like