`
zachary.guo
  • 浏览: 482987 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

让 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 来测试你的配置是否成功。
分享到:
评论
1 楼 sven.lu 2013-06-13  
怎么设置设  web 的根目录

相关推荐

    nginx-fcgi

    Nginx 不能直接执行外部可执行程序,如果要让 Nginx 支持 CGI,可以考虑安装 nginx-fcgi

    nginx-fcgi.txt

    Nginx 不能直接执行外部可执行程序,如果要让 Nginx 支持 CGI,可以考虑安装 nginx-fcgi: wget http://www.nginx.eu/nginx-fcgi/nginx-fcgi.txt mv nginx-fcgi.txt /usr/sbin/nginx-fcgi chmod +x /usr/sbin/nginx-...

    在ubuntu下为nginx配置支持cgi脚本的方案

    在nginx下支持cgi脚本于支持node类似的,只要在nginx直接做个转发,转发到对应的cgi套接字就好。 使用Fcgiwrap Fcgiqwrap是另外一个CGI封装库,跟Simple CGI类似。 安装fcgiwrap apt-get install fcgiwrap 安装以后...

    nginx负载均衡 nginx+tomcat tomcat实现负责均衡

    Nginx 本身只是一个 HTTP 和反向代理服务器,它无法像 Apache 一样通过安装各种模块来支持不同的页面脚本,例如 PHP、CGI 等; Nginx 支持简单的负载均衡和容错; 支持作为基本 HTTP 服务器的功能,例如日志、...

    nginx for windows下载以及详细安装与配置

    2.Nginx 本身只是一个HTTP和反向代理服务器,它无法像Apache一样通过安装各种模块来支持不同的页面脚本,例如PHP、CGI等 3.Nginx 支持简单的负载均衡和容错 4.支持作为基本 HTTP 服务器的功能,例如日志、压缩、Byte...

    第4章 Nginx与PHP(FastCGI)的安装、配置与优化

    Nginx不支持对外部程序的直接调用或者解析,所有的外部程序(包括PHP)必须通过FastCGI接口来调用。FastCGI接口在Linux下是socket,(这个socket可以是文件socket,也可以是ip socket)。为了调用CGI程序,还需要一...

    web服务器nginx+部署前端vue项目

    Nginx 可以作为静态页面的 web 服务器,同时还支持 CGI 协议的动态语言,比如 perl、php 等。但是不支持 java。Java 程序只能通过与 tomcat 配合完成。Nginx 专为性能优化而开发, 性能是其最重要的考量,实现上非常...

    Nginx文件上传模块配置

    也是IMAP/POP3/SMTP代理服务器,是由俄罗斯人lgor Sysoev开发,支持模块加载和卸载,其中upload_module和upload_progress_module就是第三方开发的模块,并没有加入到Nginx的源码中,upload_module是上传文件到服务器...

    nginx-1.4.7

    Nginx 本身只是一个 HTTP 和反向代理服务器,它无法像 Apache 一样通过安装各种模块来支持不同的页面脚本,例如 PHP、CGI 等; Nginx 支持简单的负载均衡和容错; 支持作为基本 HTTP 服务器的功能,例如日志、压缩、...

    window可用cgi程序(c/c++)

    window下可用的cgi程序 在window下,配合nginx和spawn-fcgi使用,内附源码和使用方法。

    markdownjs-cgi:用于提供降价文件的 nginx 配置

    markdownjs-cgi 用于为 Markdown 文件提供 HTML 的 CGI 脚本和配置。 Markdown 生成发生在客户端使用 javascript markdown 库()。 cgi shell 脚本为转换创建 HTML 框架和 javascript。 包含一个 Dockerfile,...

    nginx安装及配置支持php的教程(全)

    pcre-7.8.tar.gz 正则表达式下载地址:ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ nginx-0.7.26.tar下载地址:http://www.nginx.net/ php-5.2.6.tar.bz2下载地址:http://www.php.net/releases/ ...

    PHP Nginx MySql 绿色WEB服务器 RTMP FOR WINDOWS

    默认时启动webServer.exe自动运行Nginx、PHPCGI、Mysql。 # 如果启动服务报错 请进去运行环境目录安装两个文件即可。 # 支持直播rtmp配置 修改配置文件 nginx.conf 最后一行 # 去除 修改配置文件 default.conf ...

    《APMServ 5.2.6》:一键快速搭建Apache+PHP+MySQL+Nginx+Memcached+ASP平台的绿色软件

     ㈠Perl、CGI支持(需下载ActivePerl):  APMServ 5.2.6 附带的是MiniPerl,可以运行简单的Perl、CGI程序。如果运行复杂的Perl、CGI程序,请下载ActivePerl,安装在APMServ所在分区根目录下的usr目录中。假如...

    Nginx优化与防盗链实践教程

    但是Nginx并不支持cgi方式运行,原因是可以减少因此带来的一些程序上的漏洞。所以必须使用FastCGI方式来执行PHP程序。由于Nginx本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为自己

    Ubuntu中Nginx的安装与配置详细说明

    1.Nginx介绍  Nginx是一个非常轻量级的HTTP服务器,Nginx,它的... (2)通过CGI来实现,这个就好比之前perl的CGI,该种方式的缺点是性能差,因为每次服务器遇到 这些脚本都需要重新启动脚本解析器来执行脚本然后将结

    WNMP环境安装包Win7-Nginx-PHP5.3

    在WINDOWS环境下搭建专业Nginx-PHP WEB服务器,采用fast-cgi方式,支持高并发。没有集成Mysql,另外安装即可。

    Easy-Nginx-VHostMaker::high_voltage:Nginx虚拟主机,变得简单!!

    Nginx VHost Maker v0.12简化您的生活:)描述该工具仅适用于Linux Debian Familly,支持PHP 5.6 FPM,仅适用于Development(不适用于生产) 。 在Ubuntu 14.04上测试成功。准备 Debian Linux,Ubuntu等(Debian Fams...

Global site tag (gtag.js) - Google Analytics