搭建 CentOS+NGINX+Spawn-fcgi+CPP 开发环境

今天尝试搭建了个 CentOS+NGINX+Spawn-fcgi+CPP 的开发环境。

测试环境

  • CentOS
  • Nginx

安装 GCC、GCC-C++ 等工具

1
yum install gcc gcc-c++ autoconf automake

安装 Spawn-fcgi

1
yum install fcgi-devel spawn-fcgi

编写 FCGI 程序并编译

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdlib.h>
#include <fcgi_stdio.h>

int main(int argc, char **argv) {
int count = 0;
while(FCGI_Accept() >= 0)
printf("Content-type: text/html\n\n"
"<html><head><title>FastCGI Hello!</title></head>\n"
"<body><h1>FastCGI Hello!</h1>\n"
"Request number %d running on host <i>%s</i></body></html>\n",
++count, getenv("SERVER_NAME"));
return 0;
}

保存为 hello.cpp,然后编译:

1
gcc -o hello.cgi hello.cpp -lfcgi

Spawn-fcgi 执行 FCGI 程序

1
2
[root@localhost ~]# spawn-fcgi -p 3000 -f /data/web/fcgi/hello.cgi 
spawn-fcgi: child spawned successfully: PID: 2956

监听 3000 端口,执行刚刚编译的 FGCI 程序。可以看到执行完进程 ID 是 2956。如果要结束进程,用 kill 命令即可。

配置 Nginx

1
vim /etc/nginx/conf.d/default.conf

修改配置为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
server {
listen 80;
server_name localhost;

#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;

#location / {
# root /usr/share/nginx/html;
# index index.html index.htm;
#}

#Broly: FCGI Config
location / {
root /data/web/fcgi;
index index.cgi;
}

location ~ \.cgi$ {
fastcgi_pass 127.0.0.1:3000;
fastcgi_index index.cgi;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}

保存并退出。然后重启 Nginx:

1
systemctl restart nginx.service

浏览 FCGI 页面

CentOS+NGINX+Spawn-fcgi+CPP

参考资料