如何在在Nginx上运行Shell脚本?

前因

  • 在部署Smokeping过程中,不熟悉Apache2的配置。
  • 强硬使用Nginx替换之,最困难的就是要搞定CGI运行的问题。

后果

  • 在Nginx上跑一个Shell脚本

前置部署

  • Nginx不支持运行CGI程序,需要借助 fcgiwrapCGI转成 FastCGI
apt-get -y install nginx fcgiwrap
  • 建议将fcgiwrap监听权限设置成和Nginx保持一致,以www-data为例:
# /etc/init.d/fcgiwrap
FCGI_SOCKET_OWNER="www-data"
FCGI_SOCKET_GROUP="www-data"
  • 启动后会监听 unix:/var/run/fcgiwrap.socket
    fcgiwrap运行状态

配置服务

  • Nginx的关键配置如下:
server {
    listen       23333 backlog=233;
    charset utf-8;
    location / {
        root /data/smokeping/htdocs;
        access_log off;
        log_not_found off;
        index smokeping.cgi;
    }
    location ~ ^/.*\.(cgi|sh) {  # 主要是这里
        gzip off;
        default_type  text/plain;
        root   /data/smokeping/htdocs;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_index smokeping.cgi;
        fastcgi_pass  unix:/var/run/fcgiwrap.socket;
        allow 121.22.33.3;
        deny all;
    }
    location ~ ^(.*)\/\.(svn|git|hg|bzr|cvs)\/ {
        deny all;
        access_log off;
        log_not_found off;
    }
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    location /do_not_delete.html {
        access_log off;
        return 200;
    }
}

功能验证

  • 此时在/data/smokeping/htdocs目录下的 *.cgi*.sh 将会被执行。
#!/bin/bash
# /data/smokeping/htdocs/start.sh
echo -ne "Content-Type:text/html;charset=utf-8\r\n\r\n"
echo "<h3>$0</h3><hr><pre>$(top -bcHin1)</pre>"
exit 0

运行效果

  • 大功告成,接下来任你发挥。

猜你喜欢

转载自my.oschina.net/higkoo/blog/1801228
今日推荐