安装设置让Nginx支持CGI

废话就不多说了,开始。。。

    道理:

    Nginx默许不支撑CGI,但是支撑FastCGI,所以可以用FastCGI代替CGI。

    

    备准条件:

    1、安装perl:略

    2、 安装FCGI-ProcManage

simba@simba-laptop:~/tmp$ wget http://search.cpan.org/CPAN/authors/id/G/GB/GBJK/FCGI-ProcManager-0.19.tar.gz 
        simba@simba-laptop:~/tmp$ tar -zxvf ./FCGI-ProcManager-0.19.tar.gz 
        simba@simba-laptop:~/tmp$ cd FCGI-ProcManager-0.19/
        simba@simba-laptop:~/tmp/FCGI-ProcManager-0.19$ perl Makefile.PL 
        simba@simba-laptop:~/tmp/FCGI-ProcManager-0.19$ make;sudo make install;

   3、安装Perl FastCGI 模块(Can't locate FCGI.pm in @INC)

             simba@simba-laptop:~/tmp/FCGI-ProcManager-0.19$ sudo cpan FCGI

    

    编写Nginx cig守护程序:

    1、存保以下本脚为:/usr/local/bin/cgiwrap-fcgi.pl, 设置可执行权限。

#!perl
use FCGI;
use Socket;
use FCGI::ProcManager;
sub shutdown { FCGI::CloseSocket($socket); exit; }
sub restart  { FCGI::CloseSocket($socket); &main; }
use sigtrap 'handler', \&shutdown, 'normal-signals';
use sigtrap 'handler', \&restart,  'HUP';
require 'syscall.ph';
use POSIX qw(setsid);
 
END()   { }
BEGIN() { }
{
  no warnings;
  *CORE::GLOBAL::exit = sub { die "fakeexit\nrc=" . shift() . "\n"; };
};
 
eval q{exit};
if ($@) {
  exit unless $@ =~ /^fakeexit/;
}
&main;
 
sub daemonize() {
  chdir '/' or die "Can't chdir to /: $!";
  defined( my $pid = fork ) or die "Can't fork: $!";
  exit if $pid;
  setsid() or die "Can't start a new session: $!";
  umask 0;
}
 
sub main {
  $proc_manager = FCGI::ProcManager->new( {n_processes => 5} );
  $socket = FCGI::OpenSocket( "/tmp/cgiwrap-dispatch.sock", 10 )
  ; #use UNIX sockets - user running this script must have w access to the 'nginx' folder!!
  chmod 0766, "/tmp/cgiwrap-dispatch.sock";
  $request =
  FCGI::Request( \*STDIN, \*STDOUT, \*STDERR, \%req_params, $socket,
  &FCGI::FAIL_ACCEPT_ON_INTR );
  $proc_manager->pm_manage();
  if ($request) { request_loop() }
  FCGI::CloseSocket($socket);
}
 
sub request_loop {
  while ( $request->Accept() >= 0 ) {
    $proc_manager->pm_pre_dispatch();
 
    #processing any STDIN input from WebServer (for CGI-POST actions)
    $stdin_passthrough = '';
    { no warnings; $req_len = 0 + $req_params{'CONTENT_LENGTH'}; };
    if ( ( $req_params{'REQUEST_METHOD'} eq 'POST' ) && ( $req_len != 0 ) ) {
      my $bytes_read = 0;
      while ( $bytes_read < $req_len ) {
        my $data = '';
        my $bytes = read( STDIN, $data, ( $req_len - $bytes_read ) );
        last if ( $bytes == 0 || !defined($bytes) );
        $stdin_passthrough .= $data;
        $bytes_read += $bytes;
      }
    }
 
    #running the cgi app
    if (
      ( -x $req_params{SCRIPT_FILENAME} ) &&    #can I execute this?
      ( -s $req_params{SCRIPT_FILENAME} ) &&    #Is this file empty?
      ( -r $req_params{SCRIPT_FILENAME} )       #can I read this file?
    ) {
      pipe( CHILD_RD,   PARENT_WR );
      pipe( PARENT_ERR, CHILD_ERR );
      my $pid = open( CHILD_O, "-|" );
      unless ( defined($pid) ) {
        print("Content-type: text/plain\r\n\r\n");
        print "Error: CGI app returned no output - Executing $req_params{SCRIPT_FILENAME} failed !\n";
        next;
      }
      $oldfh = select(PARENT_ERR);
      $|     = 1;
      select(CHILD_O);
      $| = 1;
      select($oldfh);
      if ( $pid > 0 ) {
        close(CHILD_RD);
        close(CHILD_ERR);
        print PARENT_WR $stdin_passthrough;
        close(PARENT_WR);
        $rin = $rout = $ein = $eout = '';
        vec( $rin, fileno(CHILD_O),    1 ) = 1;
        vec( $rin, fileno(PARENT_ERR), 1 ) = 1;
        $ein    = $rin;
        $nfound = 0;
 
        while ( $nfound = select( $rout = $rin, undef, $ein = $eout, 10 ) ) {
          die "$!" unless $nfound != -1;
          $r1 = vec( $rout, fileno(PARENT_ERR), 1 ) == 1;
          $r2 = vec( $rout, fileno(CHILD_O),    1 ) == 1;
          $e1 = vec( $eout, fileno(PARENT_ERR), 1 ) == 1;
          $e2 = vec( $eout, fileno(CHILD_O),    1 ) == 1;
 
          if ($r1) {
            while ( $bytes = read( PARENT_ERR, $errbytes, 4096 ) ) {
              print STDERR $errbytes;
            }
            if ($!) {
              $err = $!;
              die $!;
              vec( $rin, fileno(PARENT_ERR), 1 ) = 0
              unless ( $err == EINTR or $err == EAGAIN );
            }
          }
          if ($r2) {
            while ( $bytes = read( CHILD_O, $s, 4096 ) ) {
              print $s;
            }
            if ( !defined($bytes) ) {
              $err = $!;
              die $!;
              vec( $rin, fileno(CHILD_O), 1 ) = 0
              unless ( $err == EINTR or $err == EAGAIN );
            }
          }
          last if ( $e1 || $e2 );
        }
        close CHILD_RD;
        close PARENT_ERR;
        waitpid( $pid, 0 );
      } else {
        foreach $key ( keys %req_params ) {
          $ENV{$key} = $req_params{$key};
        }
 
        # cd to the script's local directory
        if ( $req_params{SCRIPT_FILENAME} =~ /^(.*)\/[^\/] +$/ ) {
          chdir $1; 
        }
        close(PARENT_WR);
        #close(PARENT_ERR);
        close(STDIN);
        close(STDERR);
 
        #fcntl(CHILD_RD, F_DUPFD, 0);
        syscall( &SYS_dup2, fileno(CHILD_RD),  0 );
        syscall( &SYS_dup2, fileno(CHILD_ERR), 2 );
 
        #open(STDIN, "<&CHILD_RD");
        exec( $req_params{SCRIPT_FILENAME} );
        die("exec failed");
      }
    } else {
      print("Content-type: text/plain\r\n\r\n");
      print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is not executable by this process.\n";
    }
  }
}
    每日一道理
今天阳光很好,坐在窗前,看窗外如此晴朗的天感觉特别舒心,雨过天晴后的世界总给人一种明媚,仿佛阳光照耀在“心田”上空,让前些天被风雨践踏的花朵重新得到爱的关怀,重现生命的活力!

    

    将nginx cgi守护进程为开机自启动

    root@SNDA-192-168-1-58:~/hd1/bin# echo "/usr/local/bin/cgiwrap-fcgi.pl&" > /etc/init.d/nginx-cgi 

    root@simba-laptop:/home/simba/tmp# chmod 755 /etc/init.d/nginx-cgi 

    root@SNDA-192-168-1-58:~/hd1/bin# update-rc.d nginx-cgi defaults 23

    

    配置Nginx

set $web_root  /var/www/nginx-default;	#设置变量 web_root
	...

	location / {
		root   $web_root;
		index  index.html index.htm;
	}

	location ~ .*\.cgi$ {
		gzip off; #gzip makes scripts feel slower since they have to complete before getting gzipped
		fastcgi_pass  unix:/tmp/cgiwrap-dispatch.sock;


		fastcgi_index index.cgi;
		fastcgi_param SCRIPT_FILENAME  $web_root$fastcgi_script_name;
		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 GATEWAY_INTERFACE  CGI/1.1;
		fastcgi_param SERVER_SOFTWARE    nginx;
		fastcgi_param SCRIPT_NAME        $fastcgi_script_name;
		fastcgi_param REQUEST_URI        $request_uri;
		fastcgi_param DOCUMENT_URI       $document_uri;
		fastcgi_param DOCUMENT_ROOT      $web_root;
		fastcgi_param SERVER_PROTOCOL    $server_protocol;
		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;
		#include /root/hd1/conf.d/nginx/fcgi-parms
	}

    测试:

    将以下本脚存保到web根目录下,用浏览器访问。

    cgi-test.cgi

#!/usr/bin/perl

print "Content-type: text/html\n\n";
print "<html><body>Hello, world.</body></html>";

    http://localhost/cgi-test.cgi

    cgi-test-python.cgi

#!/usr/bin/python


print "Content-type: text/html\n\n"
print "<html><body>Hello, world. Hello, Python.</body></html>"

    http://localhost/cgi-test-python.cgi

    

    参考:

http://wiki.nginx.org/NginxSimpleCGI
让 Nginx 支撑 cgi
Nginx + nagios +perl fcgi

    实战Nginx与PHP(FastCGI)的安装、配置与优化

    为了AWSTATS给NGINX添加FASTCGI方式的PERL支撑

    

文章结束给大家分享下程序员的一些笑话语录: 程序语言综述
CLIPPER 程序员不去真的猎捕大象,他们只是购买大象部分的库然后花几年的时间试图综合它们。
DBASE 程序员只在夜间猎捕大象,因为那时没人会注意到他们还在使用石弓。
FOXPRO 程序员开始使用更新更好的步枪,这使他们花掉比实际狩猎更多的时间学习新的射击技术。
C 程序员拒绝直接购买步枪,宁可带着钢管和一个移动式机器车间到非洲,意欲从零开始造一枝完美的步枪。
PARADOX 程序员去非洲时带着好莱坞关于猎捕大象的电影剧本,他们认为照剧本行事就会逮到一头大象。
ACCESS 程序员在没有任何猎象经验的经验下就出发了,他们穿着华丽的猎装、带着全部装备,用漂亮的望远镜找到了大象,然后发觉忘了带扳机。
RBASE 程序员比大象还要稀少,事实上,如果一头大象看到了一个RBASE程序员,对他是个幸运日。
VISUAL ACCESS 程序员装上子弹、举起步枪、瞄准大象,这使大象感到可笑,究竟谁逃跑。他们无法抓住大象,因为由于他们对多重控制的偏爱,他们的吉普车有太多的方向盘因而无法驾驶。
ADA、APL和FORTRAN 程序员与圣诞老人和仙女一样是虚构的。
COBOL 程序员对和自己一样濒临灭绝的大象寄予了深切的同情。

posted @ 2013-04-21 10:42  坚固66  阅读(849)  评论(0编辑  收藏  举报