Nginx : Rewrite Rule for Wallpaper Site Creator

May 27, 2009 by  
Filed under Open Source Software

Nginx is a lightweight web server and mail proxy server. It was written by Igor Sysoev. Compare to Apache web server, nginx uses less resources. Beside that nginx configuration is pretty simple and easy to understand. If you using Apache and want to switch to nginx. The only thing that you should take care is your rewrite rule. As you know nginx doesn’t support .htaccess, you have to completely rewrite all of yours rewrite rule. But today I will share my rewrite rule for Wallpaper Site Creator script.


Below is the rewrite rule in the .htaccess for Apache :

Options +FollowSymlinks

RewriteEngine On
RewriteRule ^category/([0-9A-Za-z\+\_\-]+)/$ /categories.php?Category=$1 [nc]
RewriteRule ^category/([0-9A-Za-z\+\_\-]+)/([0-9]+)/$ /categories.php?Category=$1&page=$2 [nc]
RewriteRule ^wallpaper/([0-9A-Za-z\_\-]+)/$ /details.php?Title=$1 [nc]
RewriteRule ^images/wmwallpapers/(.+)$ /watermark.php?k=$1 [nc]

To apply the same rewrite rules to nginx. Paste the following rule to your nginx.conf or in your nginx virtual host configuration file.

if (!-e $request_filename) {
rewrite ^/category/([0-9A-Za-z\+\_\-]+)/$ /categories.php?Category=$1 last;
rewrite ^/category/([0-9A-Za-z\+\_\-]+)/([0-9]+)/$ /categories.php?Category=$1&page=$2 last;
rewrite ^/wallpaper/([0-9A-Za-z\_\-]+)/$ /details.php?Title=$1 last;
rewrite ^/images/wmwallpapers/(.+)$ /watermark.php?k=$1 last;
}

You should put it inside the location / {} section. Below is my virtual host configuration file after applying the rewrite rule.

server {
listen       80;
server_name  wallpapers.com;

error_log   logs/error-wallpapers.log;
access_log  logs/access-wallpapers.log;

location / {
root   /var/www/wallpapers.com;
index  index.html index.htm index.php;

if (!-e $request_filename) {
rewrite ^/category/([0-9A-Za-z\+\_\-]+)/$ /categories.php?Category=$1 last;
rewrite ^/category/([0-9A-Za-z\+\_\-]+)/([0-9]+)/$ /categories.php?Category=$1&page=$2 last;
rewrite ^/wallpaper/([0-9A-Za-z\_\-]+)/$ /details.php?Title=$1 last;
rewrite ^/images/wmwallpapers/(.+)$ /watermark.php?k=$1 last;
}
}

location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /var/www/wallpapers.com$fastcgi_script_name;
fastcgi_index index.php;
include /usr/local/nginx/conf/fastcgi_params;
}

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}

location ~ /\.ht {
deny all;

Congratulation, you will now have a Wallpaper Site Creator script work on nginx web server. If you need any help or want to add any suggestion please do not hesitate to leave your comments. :)