.htaccess condition to prevent missing CSS, JS, image urls being parsed by SilverStripe

Posted in Apache and SilverStripe -

The default .htaccess file for SilverStripe runs all URLs that do not belong to actual files on the filesystem through the Sapphire framework. This means that if a request is made for a CSS file that does not exist, for example, it will be run through SilverStripe/Sapphire, which is not really necessary.

Prevent missing CSS, JS, JPG, GIF, PNG, TXT etc being parsed by SilverStripe

The default .htaccess file looks like this:

### SILVERSTRIPE START ###
<Files *.ss>
Order deny,allow
Deny from all
Allow from 127.0.0.1
</Files>

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^(.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* sapphire/main.php?url=%1&%{QUERY_STRING} [L]
### SILVERSTRIPE END ###

Simply add a rewrite condition to ignore files with a particular extension as shown in the second example below. I've highlighted the rule by making it red.

### SILVERSTRIPE START ###
<Files *.ss>
Order deny,allow
Deny from all
Allow from 127.0.0.1
</Files>

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^(.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(css|gif|ico|jpg|js|png|swf|txt)$
RewriteRule .* sapphire/main.php?url=%1&%{QUERY_STRING} [L]
### SILVERSTRIPE END ###

If the file exists it will not be parsed by SilverStripe (as was always the case) and now if it does not exist then Apache will handle the 404 instead of leaving it to SilverStripe. If you prefer to leave SilverStripe to handle the 404 then don't add this line.




Comments