Search This Blog

Friday, August 3, 2007

Move from apache 2.2 to Nginx as a PHP or Ruby web server

Recently we started to move moderately loaded news web site from apache 2.2 to Nginx due to it's incredible performance and security.

So, here the short instruction set to start Nginx with PHP and RubyOnRails under daemontools monitoring on FreeBSD:

PHP:
cat /var/services/backend-phpfcgi/run
#!/bin/sh
exec 2>&1
exec setuidgid backend spawn-fcgi -n -a 127.0.0.1 -p 9000 -f /usr/local/bin/php-cgi

I'm using spawn-fcgi from lighttpd package, however the php-cgi can be ran directly.

RubyOnRail:
cat /var/services/backend-rubyfcgi/run
#!/bin/sh
umask 22
export RAILS_ENV=production
exec setuidgid rubysite spawn-fcgi -n -a 127.0.0.1 -p 9001 -f /home/rubysite/www/public/dispatch.fcgi

Nginx configuration files:

cat /usr/local/etc/nginx/nginx.conf
user www;
worker_processes 30;
timer_resolution 1000ms;

error_log /var/log/nginx-error.log error;
pid /var/run/nginx.pid;

events {
worker_connections 2048;
use kqueue;
}


http {
include mime.types;
default_type application/octet-stream;

access_log off;
gzip on;
gzip_comp_level 6;

sendfile on;
#tcp_nopush on;

keepalive_timeout 65;

include vhosts/conf-*;
server {
listen ip.add.re.ss:80 default accept_filter=httpready;

error_page 404 /404.html;
location / {
root /home/default/www;
index index.html;
}
}
}

cat /usr/local/etc/nginx/vhosts/conf-site.com
server {
listen ip.add.re.ss;
server_name site.com www.site.com

location / {
root /home/site/www;
index index.php;
}

location ~* ^.+\.(php)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/site/www/$fastcgi_script_name;

include fastcgi_params;
}
}

cat /usr/local/etc/nginx/fastcgi_params

fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;

fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;

fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;

fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;


Nginx runs under www privileges and the back-end as a backend user so security is much improved.

P.S.
Interesting link shows nginx as third popular web server.