.htaccess: Serve static files, route everything else to index.php

mpen picture mpen · Sep 21, 2014 · Viewed 9.4k times · Source

I want to use an .htaccess file to check if the requested path is a file in the public/ directory. If yes, serve it, else forward request to /index.php. I can't seem to get this to work.

Here's what I've got:

Options +FollowSymLinks
RewriteEngine on

Options -Indexes

RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f
RewriteRule ^ %{DOCUMENT_ROOT}/public%{REQUEST_URI} [L]

RewriteRule ^ index.php [QSA,L]

e.g. http://example.com/css/style.css should have apache serve /public/css/style.css because it's a file that exists, but http://example.com/css/style.bad should be sent to /index.php.

Answer

Justin Iurman picture Justin Iurman · Sep 21, 2014

This code should be working as expected on your side

Options +FollowSymLinks -MultiViews -Indexes

RewriteEngine On
RewriteBase /

RewriteCond %{DOCUMENT_ROOT}/public/$1 -f
RewriteRule ^(.*)$ public/$1 [L]

RewriteCond %{THE_REQUEST} \s/public/ [NC,OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L,QSA]