nginx cgi 配置

nginx 本身是不能执行外部程序的,nginx 处理 PHP 也是通过 PHP 的 fcgi 管理器进行处理,然后 nginx 再将结果返回给用户;所以如果我们需要通过 cgi 程序来编写网站后台的话,就需要 spawn-fcgi 和 fcgiwrap 帮助 nginx 处理 cgi。

安装epel源

yum -y install epel-release

安装fcgi

yum -y install fcgi fcgi-devel

安装spawn-fcgi

yum -y install spawn-fcgi

安装fcgiwrap

git clone git://github.com/gnosek/fcgiwrap.git
cd fcgiwrap
autoreconf -i
./configure
make
make install

配置spawn-fcgi

vim /etc/sysconfig/spawn-fcgi
--- spawn-fcgi ---
FCGI_SOCKET=/var/run/fcgiwrap.socket
FCGI_PROGRAM=/usr/local/sbin/fcgiwrap
FCGI_USER=nginx
FCGI_GROUP=nginx
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"
## -F 1 表示启动一个 fcgiwrap 进程,有需要的可以多启动几个

配置nginx

server {
    root /usr/share/nginx/html;
    index index.html;
    location /cgi-bin/ {
        fastcgi_pass unix:/var/run/fcgiwrap.socket;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

### 配置优化
http {
    client_max_body_size 1G;
    fastcgi_connect_timeout 120;
    fastcgi_send_timeout 120;
    fastcgi_read_timeout 120;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
}

cgi-bin目录

cd /usr/share/nginx/html
mkdir cgi-bin
chown nginx:nginx cgi-bin

## 新建一个cgi程序
vim hello.py

--- hello.py ---
#!/usr/local/python-3.5.2/bin/python3.5
print('Content-type: text/html\r\n')
print(<h1>-------------> Hello, world! <---------------</h1>)
--- hello.py ---

## 修改权限
chown nginx:nginx hello.py
chmod +x hello.py

启动服务

service spawn-fcgi start
service nginx restart

cgi 测试

nginx-fcgi