前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++使用Nginx搭建WEB程序

C++使用Nginx搭建WEB程序

原创
作者头像
lingxh
修改2021-12-03 15:12:28
2.1K0
修改2021-12-03 15:12:28
举报
文章被收录于专栏:lingxhlingxh

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

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

安装 fcgiwrap

快速安装:

代码语言:javascript
复制
//centos系统安装:
yum -y install fcgiwrap

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

编译安装:

代码语言:javascript
复制
//安装必要依赖:
//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

代码语言:javascript
复制
//启动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示例代码

代码语言:javascript
复制
#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;
}

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

代码语言:javascript
复制
[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的配置文件,添加以下代码

代码语言:javascript
复制
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配置

最后访问http://127.0.0.1:9001/

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装 fcgiwrap
  • 启动 fcgiwrap
  • C++ CGI示例代码
  • Nginx配置
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档