Nginx rewrite rules for SilverStripe CMS

If you are using Nginx with a configuration that is directly serving php pages via FastCGI, you need to adapt the rewrite rules to Nginx. In the case of the CMS-system SilverStripe this is not really straight forward. The original rewrite definition in the .htaccess file looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !(\.gif)|(\.jpg)|(\.png)|(\.css)|(\.js)|(\.php)$

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

So every file which does not end in .gif, .jpg, .png, .css, .js and .php and where the file does not exist will be rewritten.

I chose a somehow stripped down version of these rules which looks in Nginx notation like this:

if (!-f $request_filename) {
    rewrite ^/(.*?)(\?|$)(.*)$ /sapphire/main.php?url=$1&$3 last;
}

If a requested file is not found, the rewriting engine will parse the request string for all elements before a ‘?’. This substring will be pasted as the url parameter to main.php. Everything after ‘?’ will be added as additional parameters. This rewrite rule seems to be working and I haven’t encountered any problems so far.

Leave a Reply