nginx本身不支持直接调用shell脚本,我们可以通过安装fastcgi程序,让nginx把调用shell的http请求交给fastcgi程序去处理,然后nginx 再将结果返回给用户方式间接调用shell,这里我们推荐安装fcgiwrap这个通用的 fastcgi 进程管理器来帮助nginx 处理shell程序

一、安装fcgiwrap

   

# 安装 epel 源
yum -y install epel-release

# 安装 fcgi 依赖
yum -y install fcgi fcgi-devel

# 安装 fcgiwrap
wget https://github.com/gnosek/fcgiwrap/archive/master.zip
unzip master.zip
cd fcgiwrap-master
autoreconf -i
./configure
make
make install

通过执行以上命令将会把fcgiwrap安装到/usr/local/sbin/fcgiwrap这个路径

二、安装spawn-fcgi

    通过安装spawn-fcgi方便启动fcgiwrap程序

#安装spawn-fcgi
yum install spawn-fcgi
修改/etc/sysconfig/spawn-fcgi配置文件
vi /etc/sysconfig/spawn-fcgi

   修改配置文件为以下内容

# You must set some working options before the "spawn-fcgi" service will work.
# If SOCKET points to a file, then this file is cleaned up by the init script.
#
# See spawn-fcgi(1) for all possible options.
#
# Example :
#SOCKET=/var/run/php-fcgi.sock
#OPTIONS="-u apache -g apache -s $SOCKET -S -M 0600 -C 32 -F 1 -P /var/run/spawn-fcgi.pid -- /usr/bin/php-cgi"
FCGI_SOCKET=/var/run/fcgiwrap.socket
FCGI_PROGRAM=/usr/local/sbin/fcgiwrap
FCGI_USER=nobody
FCGI_GROUP=nobody
FCGI_EXTRA_OPTIONS="-M 0700"
OPTIONS="-u $FCGI_USER -g $FCGI_GROUP -s $FCGI_SOCKET -S $FCGI_EXTRA_OPTIONS -F 1 -P /var/run/spawn-fcgi.pid -- $FCGI_PROGRAM"

   添加spawn-fcgi开机启动服务

chkconfig --levels 235 spawn-fcgi on

  启动spawn-fcgi服务

/etc/init.d/spawn-fcgi start

三、配置nginx执行shell调用

      修改nginx配置文件

vi /usr/local/nginx/conf/nginx.conf

    增加以下内容

 location ~ ^/.*\.sh  {
          gzip off;
          root /home/shell; #shell文件存放目录
          fastcgi_pass  unix:/var/run/fcgiwrap.socket;
          include fastcgi_params;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

四、创建shell文件

vi /home/shell/hello.sh

      添加以下内容

#!/bin/bash
echo "Content-Type:text/html"
echo "" 
echo "hello world!"

     添加shell脚本执行权限

chmod -R 755 /home/shell

然后在浏览器中输入http://<ip>:port/hello.sh

即可调用我们的shell脚本

 说明:

 1、脚本前三行是必须的,第一行用于指定脚本执行使用的解释器,第二行和第三行是HTTP协议规范,在发送HTML正文之前要发送MIME头和空行

 2、shell脚本都是使用nobody用户执行的,所以要确保nobody可以读取并执行hello.sh

    参考文档:https://www.howtoforge.com/serving-cgi-scripts-with-nginx-on-centos-6.0-p2