Skip to main content

用 Apache 及 C++ 搭建 FastCGI Web 服务指南

技术
Author

cookwhy

Published

July 22, 2012

FastCGI 用来作为 Web 服务器的设计方案,有着很多优点。要搭建这样一个服务,有一个最简单的办法来搭建,可以使用 Apache 以及 mod_fcgid 模块来实现。

鉴于网上有关 FastCGI 的中文资料(尤其是实战资料)比较少,下面就用 Ubuntu 11.04 及 Apache2.2 为例,说明一下 FastCGI 服务器配置的基本流程。

Apache 及 mod_fcgid 模块的配置

<p>
  首先,正确安装 <a href="http://blog.waterlin.org/articles/lamp-apache-virtualhost-setting.html">Apache</a>,这个直接从命令行安装就可以了:
</p>

<pre>
$ sudo apt-get install apache2
<p>
  然后,再安装 mod_fcgid 模块,同样可以直接从命令行安装:
</p>

<pre>
$ sudo apt-get install libfcgi-dev
<p>
  安装好 Apache 及 mod_fcgid 模块以后,再到配置文件
</p>

<pre>
/etc/apache2/sites-enabled/000-default
<p>
  里配置一下有关 mod_fcgid 的选项(注意,根据 Apache 版本及安装方式不同,配置文件所在路径会有所不同,详细情况请<a href="http://blog.waterlin.org/articles/lamp-apache-virtualhost-setting.html">查阅 Apache 手册</a>),配置示例如下所示:
</p>

<pre>

<Directory /var/www/> SetHandler fcgid-script Options +ExecCGI

Customize the next two directives for your requirements.

Order allow,deny Allow from all </Directory>
<p>
  这里配置的目录,是指把后面编译好的 FastCGI 程序放到目录 <strong>/var/www/</strong> 下,当然,你也可以选择任意一个 Apache 有权限运行的目录。
</p></p>

安装 fcig 开发库

<p>
  在 Linux 下,需要安装库 <a href="http://www.fastcgi.com/devkit/doc/overview.html">libfcgi</a> 才能在 C, C++, Java, Perl 等程序下开发 FastCGI 功能,这样才能在 C/C++ 程序里正确使用 FastCGI,fcgi 库把 FastCGI 封装好了,你不需要关注 FastCGI 协议的任何细节。可以使用下面的命令来安装:
</p>

<pre>
$ sudo apt-get install libfcgi-dev
<p>
  在你的工作目录里新建一个 .c 文件,并输入下面这段代码,并保证可以正确编译:
</p>

<pre>

#include “fcgi_stdio.h” #include <stdlib.h>

void main(void) { int count = 0; while(FCGI_Accept() >= 0) printf(“Content-type: text/html” “” “<title>FastCGI Hello!</title>” “<h1>FastCGI Hello!</h1>” “Request number %d running on host <i>%s</i>”, ++count, getenv(“SERVER_NAME”)); }
<p>
  使用下面的命令编译上述代码:
</p>

<pre>
$ gcc tiny-fcgi.c -o tiny-fcgi -lfcgi
<p>
  编译好的 FastCGI 程序应该可以直接运行(是的,就像普通可执行程序一样),会输出相关的结果,你可以试试。
</p>

<p>
  然后把编译出来的文件,拷贝到上面 Apache 设置的 FastCGI 程序可执行目录里:
</p>

<pre>
$ cp tiny-fcgi /var/www/

访问你的 FastCGI 服务

<p>
  重启 Apache 服务:
</p>

<pre>
$ sudo /usr/sbin/apachectl restart
<p>
  然后在浏览器里输入类似下面的网址,就可以访问这个 FastCGI 提供的服务了:
</p>

<pre>
http://127.0.0.1/tiny-fcgi

小结

<p>
  上述整体配置还算很简单,以后再介绍一些 FastCGI 高级使用技巧。FastCGI 这种比较古老的协议,特别适合用来设计需要做分布式计算、用 C 来实现计算代码的场景。服务器与计算引擎的分开,能很方便地让 Web 开发人员与后台服务器人员不受干扰,各自发挥自己的特长。
</p></p>