Melvin Rufetu February 2016

Laravel throwing 404 on images/css/js

Laravel is throwing a 404 error on my images, css and javascript files which are located in /mysite/public. I've set /mysite/public as the site's root folder and all my assets are located in there.

I did a google search on this error but they all gave the same solution i.e {{asset('css/style.css')}}. I already have my links setup like this so I don't think this is the problem.

I think the error has something to do with my Rewrite rules but I just can't figure our what it is.

My site's .htaccess file is:

RewriteEngine On
<IfModule mod_rewrite.c>
    RewriteEngine On 
    RewriteRule ^(.*)$ index.php/$1 [L]
    RewriteCond %{SERVER_PORT} 80 
    RewriteRule ^(.*)$ https://www.my-site.com/$1 [R,L]

</IfModule>

If I delete the first RewriteRule, my css loads fine but pages other that the homepage will start throwing a 404 error. If I put it back, other page work fine but css, js and image file stop loadings.

Answers


Tom February 2016

Your first rule essentially says "regardless of what the URL is, load index.php". This means it will never load your assets, which are physical folders, as it will just load index.php instead. For example, if you tried to load css/image.png it will just load index.php.

If you remove it, your actual folders will load, but other URLs aren't re-written to index.php, which is why it will break.

You should use the .htaccess provided to you by Laravel. This should be your .htaccess file in the public/ folder (as per the Laravel Github repository)

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

public/.htaccess

If the public folder is not the root on your server, you'll also need to have this in an additional .htaccess (in the folder above public)

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

/.htaccess


WebChemist February 2016

add this rule to keep assets from being routed to the router

RewriteEngine On

# Don't rewrite for css/js/img assets
RewriteRule ^assets/.* - [L]

RewriteRule ^(.*)$ index.php/$1 [L]
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.my-site.com/$1 [R,L]

Post Status

Asked in February 2016
Viewed 2,940 times
Voted 5
Answered 2 times

Search




Leave an answer