C++使用Nginx搭建WEB程序

2k 词

Nginx 不能像Apache那样直接执行外部可执行程序,但Nginx可以作为代理服务器,将请求转发给后端服务器,这也是nginx的主要作用之一。其中nginx就支持FastCGI代理,接收客户端的请求,然后将请求转发给后端FastCGI进程。下面介绍如何使用C/C++编写CGI/FastCGI,并部署到Nginx中。

安装Nginx过程省略,不懂的可以Bing,Google,Baidu


安装 fcgiwrap

快速安装:

1
2
3
4
5
//centos系统安装:
yum -y install fcgiwrap

//ubuntu系统安装:
apt -y install fcgiwrap

编译安装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//安装必要依赖:
//centos系统安装:
yum install git-core build-essential libfcgi-dev autoconf libtool automake
//ubuntu系统安装:
apt install git-core build-essential libfcgi-dev autoconf libtool automake


//从github拉取文件
cd /usr/local/src/
git clone https://github.com/gnosek/fcgiwrap.git

//编译安装
cd /usr/local/src/fcgiwrap
autoreconf -i
./configure
make
mv fcgiwrap /usr/local/bin/

启动 fcgiwrap

1
2
3
4
5
6
7
8
//启动fcgiwrap
fcgiwrap -f -s unix:/var/run/fcgiwrap.socket &

//检查是否存在相关进程
ps aux grep '[f]cgiwrap'

//如果启动fcgiwrap的用户与启动nginx的用户不一样的话需要给予权限
chmod a+rw /var/run/fcgiwrap.socket

C++ CGI示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main ()
{

cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << R"(<meta charset="UTF-8">)";
cout << "<title>Hello CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<p>Hello CGI</p>";
cout << "</body>\n";
cout << "</html>\n";

return 0;
}

接下来编译,直接打开程序试着运行:

1
2
3
4
5
6
7
8
9
10
11
[root@instance ~]# g++ test.cpp -o test.cgi -std=c++11
[root@instance ~]# ./test.cgi
Content-type:text/html

<html>
<head>
<meta charset="UTF-8"><title>Hello CGI</title>
</head>
<body>
<p>Hello CGI</p></body>
</html>

把程序复制到/wwwroot/cgitest


Nginx配置

打开Nginx的配置文件,添加以下代码

1
2
3
4
5
6
7
8
9
10
11
12
server
{
listen 9001;
server_name 127.0.0.1;
root /wwwroot/cgitest;


location ~ \.cgi$ {
fastcgi_pass unix:/var/run/fcgiwrap.socket;
include fastcgi_params;
}
}

保存,重载Nginx配置


测试你的第一个CGI程序

打开浏览器,访问http://127.0.0.1:9001/test.cgi

留言