NginxとFastCGIでCGIを動かす方法

Nginx で CGI(Peal)を動かす方法です。Nginx単体では、CGIを動かすことが出来ませんので、FastCGI と連携してCGIを動かします。

※これは Debian5 では動きません。(パッケージが無いため)

FastCGI をインストール

// インストール
# apt-get install fcgiwrap

default の修正

#vi /etc/nginx/sites-available/default を修正します。
ご自分の環境に合わせて31~36行目を追記してください。

server {
	listen 80;

	root /home/hoge/example.com;
	index index.php index.html index.htm;

	server_name example.com;

	access_log /var/log/nginx/example.com-access.log;
	error_log /var/log/nginx/example.com-error.log;

	location / {
		try_files $uri $uri/ =404;
	}

	location ~ \.php$ {
		fastcgi_pass unix:/var/run/php5-fpm.sock;
		fastcgi_index index.php;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		include fastcgi_params;
		fastcgi_pass_header "X-Accel-Redirect";
		fastcgi_pass_header "X-Accel-Expires";
		fastcgi_no_cache $do_not_cache;
		fastcgi_cache_bypass $do_not_cache;
		fastcgi_cache wpcache;
		fastcgi_cache_key "$scheme://$host$request_uri";
		fastcgi_cache_valid 200 10m;
		fastcgi_cache_valid 404 1m;
	}

	location ~ \.cgi$ {
		fastcgi_pass unix:/var/run/fcgiwrap.socket;
		fastcgi_index index.cgi;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		include fastcgi_params;
	}

	location ~ \.(jpg|png|gif|swf|jpeg|ico)$ {
		expires 30d;
	}

	location ~ \.(css|js)$ {
		charset UTF-8;
		expires 30d;
	}

	location = /favicon.ico {
		log_not_found off;
		access_log off;
	}

	location = /robots.txt {
		log_not_found off;
		access_log off;
	}

	location ~ /(\.ht|\.user.ini|\.git|\.hg|\.bzr|\.svn) {
		deny  all;
	}

	error_page 500 502 503 504 /50x.html;
	location = /50x.html {
		root /usr/share/nginx/html;
	}
}

Nginxの再起動

Nginx の設定ファイルを読み込む。

// 再起動
# /etc/init.d/nginx reload

これで CGI が動くはずです。意外と簡単でしたね。

読んで頂いて有り難うございます!