Posted by & filed under Coding.

A couple days ago I ran a report over at GTMetrix and the screenshot looked terrible. No CSS was loading. Sure enough, when I went to the site it looked just as bad to me.

First thought was that it was a caching plugin that I loaded into Laravel. So I deleted the cache files and the site was back to normal. Thought it was just a weird glitch. I thought wrong.

Okay, not totally wrong. The cache was playing a role in why I was seeing the mistake. But not why it was happening.

Looking at the source of the page it was trying to load CSS from which caused issues because of the index.php in the middle.

Best guess, what was happening is that I was using the url() Laravel method instead of asset(). Seems like they do pretty much the same thing. But I came on a glitch.

If the site was visited as instead of just then the paths for the CSS files would include index.php. If that was the first view since the cache was cleared, index.php would also be included in the CSS paths. That’s why clearing the cache fixed it for me, but only temporarily.

The Fix

My first choice would have been an .htaccess solution that redirected before PHP even gets involved. But after spending more time than I wanted getting a working solution online became more important that the best solution.

What I did was to insert the following PHP code in the top of /public/index.php which is the file that boots up Laravel. It went at the top so that it happened before Laravel loads anything else up.

if (strpos($_SERVER['REQUEST_URI'], 'index.php') !== false) {
    $new_url = preg_replace('#index\.php/?#', '', $_SERVER['REQUEST_URI']);
    header('HTTP/1.1 301');
    header('Location: ' . $new_url);

Since there shouldn’t be index.php in any of the request URIs the snippet looks for it. If it’s there, it does a regex replacement that may or may not include a trailing slash. Did it that way so that it takes care of both the /index.php request, but also requests like /index.php/css/style.css and redirects correctly.

At least it works

If anyone reading this can help out with the .htaccess solution, please pass it along in the comments. I’m not a fan of having to launch PHP just to handle this.

But it does work, and should take care of bouncing whoever is including index.php in the root address to the right spot. More importantly, it should eventually take care of the few hundred URIs that Google has indexed that include index.php.

Leave a Reply

Your email address will not be published. Required fields are marked *