Saturday, 4 December 2010

Nginx rewrite rules for Interspire Shopping Cart

It's been a while since I made my last post on this blog, but that's because I've been busy with work! Anyway, today I've chosen to publish a simple finding that I've come up with myself (not that it was any difficult anyway). It could be useful for people who want to run a web shop, particularly the excellent Interspire Shopping Cart. It comes with a set of rewrite rules for Apache to enable search-engine friendly URLs, but nothing for Nginx unfortunately.

Here is the Apache .htaccess file provided with Interspire Shopping Cart. I'm only pasting the section that we are interested in, in other words the Rewrite Module section:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php   
In order to achieve the same results in Nginx, you simply need to enable this location block:
        location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
        }
The try_files directive will attempt to serve the first parameter ($uri, the URI of the client request), then the second one ($uri + slash, could be a folder), but if neither is found, it will redirect the request to index.php and specify the requested URI as parameter in the URL together with the original arguments. It's as simple as that! The PHP scripts will handle the actual rewrites themselves.

Here is the full virtual host configuration which I used on a client's server:
    server {
        listen 80;
        server_name .website.com;
        root /var/www/website.com;
        index index.php;
       
        location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }
    }
IMPORTANT NOTE: when you enable those rewrite rules in Nginx, Interspire does not automatically detect friendly URLs as being "available". So you need to go to your Interspire control panel, in the store settings, and force it to "Enable search-engine friendly URLs" instead of "Enable if available".

Enjoy!

No comments:

Post a Comment