首页 > web服务 > nginx > 配置nginx支持运行cgi
2016
05-11

配置nginx支持运行cgi

nginx 天生是不支持 cgi 的,所以 nginx 也就没有了 cgi 方面的漏洞,提高了安全性。即 nginx 不能直接执行外部可执行程序。nginx 虽然不支持 cgi,但它支持 fastCGI。所以,我们可以考虑安装 perl fcgi 来支持 cgi。

安装 perl fcgi

[root@localhost ~]# cd /usr/local/
[root@localhost /usr/local]# wget http://www.cpan.org/modules/by-module/FCGI/FCGI-0.67.tar.gz
[root@localhost /usr/local]# tar -xzxf FCGI-0.67.tar.gz
[root@localhost /usr/local]# cd FCGI-0.67
[root@localhost /usr/local/FCGI-0.67]# cd FCGI-0.67
[root@localhost /usr/local/FCGI-0.67]# perl Makefile.PL
[root@localhost /usr/local/FCGI-0.67]# make && make install

安装 FCGI-ProcManager

[root@localhost ~]# cd /usr/local/
[root@localhost /usr/local]# wget http://search.cpan.org/CPAN/authors/id/B/BO/BOBTFISH/FCGI-ProcManager-0.24.tar.gz
[root@localhost /usr/local]# tar -xzxf FCGI-ProcManager-0.24.tar.gz
[root@localhost /usr/local]# cd FCGI-ProcManager-0.24
[root@localhost /usr/local/FCGI-ProcManager-0.24]# cd FCGI-0.67
[root@localhost /usr/local/FCGI-ProcManager-0.24]# perl Makefile.PL
[root@localhost /usr/local/FCGI-ProcManager-0.24]# make && make install

准备工作做完了,下面就可以开始让 nginx 支持 cgi 之旅了。

1. 用 perl 写一个 daemon 程序来处理 cgi 文件
下面这段用 perl 写的 daemon 程序,我们命名为 cgiwrap-fcgi.pl,放入 /usr/local/bin 下。注意,这段 perl 代码的第 36 和 37 行,这两行都表示监听来自 perl CGI 的请求。其中:
127.0.0.1:8999 表示使用 TCP/IP 协议响应请求
/var/run/nginx/cgiwrap-dispatch.sock 表示使用 unix socket 响应 CGI 请求

我们的示例中,将采用 unix socket 的方式来响应 CGI 请求。

#!/usr/bin/perl -w
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);

#&daemonize; we don't daemonize when running under runsv
#this keeps the program alive or something after exec'ing perl scripts
END()   { }
BEGIN() { }
{
    no warnings;
    *CORE::GLOBAL::exit = sub { die "fakeexit\nrc=" . shift() . "\n"; };
};
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 {

    #$socket = FCGI::OpenSocket( "127.0.0.1:8999", 10 ); #use IP sockets
    #$socket = FCGI::OpenSocket( "/var/run/nginx/cgiwrap-dispatch.sock", 10 ); #use UNIX sockets - user running this script must have w access to the 'nginx'
 folder!!
    #foreach $item (keys %ENV) { delete $ENV{$item}; }

    $proc_manager = FCGI::ProcManager->new( {n_processes => 5} );
    $socket = FCGI::OpenSocket( "/var/run/nginx/cgiwrap-dispatch.sock", 10 ); #use UNIX sockets - user running this script must have w access to the 'nginx'
folder!!
    $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();
"cgiwrap-fcgi.pl" [dos] 164L, 6275C
                            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";
        }
    }
}

2. 有关 /var/run/nginx/cgiwrap-dispatch.sock
cgiwrap-dispatch.sock 文件是用来响应 CGI 请求的。实际上,文件名是随意的,甚至都可以不在 /var/run/ngin 下。即用来处理 CGI 请求的文件是完全随意的。当然,我们还是以 /var/run/nginx/cgiwrap-dispatch.sock[ 为例来讲解。

在我们的机器中,并不存在 /var/run/nginx 这样的目录,我们可以通过 mkdir 命令来建立这样层次结构的目录。至于 /cgiwrap-dispatch.sock 这个文件,通过 touch /cgiwrap-dispatch.sock 创建一个空的文件即可。

请确保在 nginx.cong 中声明的 user 的用户和组具备以下权限:
对 /var/run/nginx 具有 W 权限
对 cgiwrap-dispatch.sock 具有 W 权限

3. 在后台运行 cgiwrap-fcgi.pl

# 这种方式运行 cgiwrap-fcgi.pl 会输出日志
[root@localhost ~]# /usr/local/bin/cgiwrap-fcgi.pl
Useless use of a constant in void context at ./cgiwrap-fcgi.pl line 20.
FastCGI: manager (pid 2452): initialized
FastCGI: server (pid 2453): initialized
FastCGI: manager (pid 2452): server (pid 2453) started
FastCGI: manager (pid 2452): server (pid 2454) started
FastCGI: server (pid 2454): initialized
FastCGI: server (pid 2455): initialized
FastCGI: manager (pid 2452): server (pid 2455) started
FastCGI: server (pid 2456): initialized
FastCGI: manager (pid 2452): server (pid 2456) started
FastCGI: server (pid 2457): initialized
FastCGI: manager (pid 2452): server (pid 2457) started
FastCGI: manager (pid 2452): server (pid 2453) exited with status 2304
FastCGI: server (pid 5456): initialized
FastCGI: manager (pid 2452): server (pid 5456) started
FastCGI: manager (pid 2452): server (pid 2454) exited with status 2304
FastCGI: manager (pid 2452): server (pid 9471) started
FastCGI: server (pid 9471): initialized

这种方式运行 cgiwrap-fcgi.pl,会在控制台输出日志,这样我们确认该脚本已正常运行着的。后续若不想输出日志,可以这样来运行 cgiwrap-fcgi.pl:

# 这种方式运行 cgiwrap-fcgi.pl 不会输出日志
[root@localhost ~]# /usr/local/bin/cgiwrap-fcgi.pl > /dev/null 2>&1 &

# 这种方式运行 cgiwrap-fcgi.pl 能够使得该脚本随系统启动而启动
# 编辑 /etc/rc.local 文件,最后一行添加:
/usr/local/bin/cgiwrap-fcgi.pl > /dev/null 2>&1 & 

4. 在 web 的根目录建立 test.cgi 来测试
设 web 的跟目录为 /home/git,建立 test.cgi 文件,确保在 nginx.cong 中声明的 user 的用户和组具备对 test.cgi 的可执行权限。

[root@localhost ~]# vi /home/git/test.cgi
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello, world.";

5. 在 nginx.conf 中做如下配置

location ~ .*\.cgi$ {
    fastcgi_pass   unix:/var/run/nginx/cgiwrap-dispatch.sock;
    fastcgi_index  index.cgi;
    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
    fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
    fastcgi_param  SERVER_SOFTWARE    nginx;
    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  REQUEST_URI        $request_uri;
    fastcgi_param  DOCUMENT_URI       $document_uri;
    fastcgi_param  DOCUMENT_ROOT      $document_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;
}

你若觉得这段配置太长了,你可以将 fastcgi_param 这段配置独立成一个文件,如 fastcgi_params.conf,然后通过 include 指令将其包含进来。

到此为止,已经做到让 nginx 支持 cgi 了。你可以通过访问 http://localhost/test.cgi 来测试你的配置是否成功。
nginx-cgi

最后编辑:
作者:admin

留下一个回复