jarvis Posted April 6, 2020 Share Posted April 6, 2020 Hi All, Am having a "can't see the wood for the trees" moment I have a php redirect file which contains my URLs, like so: return [ '/shop/' => '/products/', ]; I then have a functions file which contains: function 301_redirects(){ $redirects = include __DIR__ . '/redirects.php'; if (isset($redirects[$_SERVER['REQUEST_URI']])) { header("HTTP/1.1 301 Moved Permanently"); header('location: ' . $redirects[$_SERVER['REQUEST_URI']]); exit; } if (isset($redirects[rtrim($_SERVER['REQUEST_URI'], '/')])) { header("HTTP/1.1 301 Moved Permanently"); header('location: ' . $redirects[rtrim($_SERVER['REQUEST_URI'], '/')]); exit; } } If the URL is https://www.mydomain.com/shop then the redirect won't work If the URL is https://www.mydomain.com/shop/ then the redirect works What am I missing? Thanks Quote Link to comment Share on other sites More sharing options...
requinix Posted April 6, 2020 Share Posted April 6, 2020 The redirect is configured for /shop/. With the trailing slash. Do you really have to do this with PHP? Setting up the redirect with the web server is almost definitely going to be better, and faster, and more efficient, and even simpler. I say this not just because your redirect function there isn't quite correct. Quote Link to comment Share on other sites More sharing options...
jarvis Posted April 7, 2020 Author Share Posted April 7, 2020 Thanks @requinix It's usually done this way due to the number of redirects and from an admin point of view (someone else maintains it). I thought adding both functions would cater for trailing slash and non-trailing slash I'll review it again Quote Link to comment Share on other sites More sharing options...
requinix Posted April 7, 2020 Share Posted April 7, 2020 7 minutes ago, jarvis said: I thought adding both functions would cater for trailing slash and non-trailing slash You account for trailing slashes in the request URI only. You'll test with and without the slash, but the map only has the one version. Which is fine as long as you think about which version... 7 hours ago, requinix said: I say this not just because your redirect function there isn't quite correct. Your function does not account for two important things: the request URI starting with the path (and not being only the path), and a potential query string. Slash problem aside, /shop/foo and /shop?bar will both fail to redirect. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.