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.

2 thoughts on “Nginx rewrite rules for SilverStripe CMS

  1. Well, basically changing the rewrite rules was the only challenge in getting SilverStripe to run. Once nginx is configured to run php files via FastCGI there is nothing else which needs to be configured specifically for SilverStripe.

    But I will post my complete configuration file on your wiki. Might save some time for someone who just stumbled over nginx.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">