apache对php的支持是通过apache的mod_php5模块来支持的,这点与nginx不同。nginx是通过第三方的fastcgi处理器才可以对php进行解析。
如果源码编译安装php的话,需要在编译时指定--with-apxs2=/usr/local/apache2/bin/apxs表示告诉编译器通过apache的mod_php5模块来提供对php的解析。
同时php安装的最后一步make install时,我们会看到将动态链接库libphp5.so拷贝到apache2的安装目录的modules目录下,并且还需要在httpd.conf配置文件中添加LoadModule语句来动态将libphp5.so模块加载进来,从而实现Apache对php的支持。
php与apache集成需要以下几个步骤:
1、安装libiconv库
2、php源码安装
3、配置apache使其支持php
4、测试php
一、安装libiconv库
libiconv库为需要做转换的应用程序提供了一个iconv命令,以实现一个字符编码到另一个字符编码的转换,比如它可以将UTF8编码转换成GB18030编码,反过来也行。
php与apache集成时一定要安装libiconv库,否则在make时系统会报错。报错信息如下:
make: *** [sapi/cli/php] Error 1
/usr/bin/ld: cannot find -liconv
collect2: ld returned 1 exit status
make: *** [sapi/cli/php] Error 1

现在开始正式安装libiconv库,首先下载libiconv库,如下:
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz

解压libiconv库,如下:
tar -xf libiconv-1.14.tar.gz

安装libiconv库,首先查看安装帮助信息。如下:
./configure --help

通过上图的帮助,我们可以看到libiconv库默认的安装路径为/usr/local。现在开始安装libiconv库,如下:
./configure --prefix=/usr/local
make && make install


libiconv库安装完毕后,建议把/usr/local/lib库加入到到/etc/ld.so.conf文件中,然后使用/sbin/ldconfig使其生效。如下:
echo "/usr/local/lib">>/etc/ld.so.conf
/sbin/ldconfig

如果没有进行此步操作的话,在安装php执行make install,系统就会报错。报错信息如下:
/root/php-5.6.2/sapi/cli/php: error while loading shared libraries: libiconv.so.2: cannot open shared object file: No such file or directory
二、php源码安装
下载并编译php命令如下:
wget http://mirrors.sohu.com/php/php-5.6.2.tar.gz
./configure --enable-fpm --enable-mbstring --with-mysql=/usr/local/mysql --with-iconv-dir=/usr/local --with-apxs2=/usr/local/apache2/bin/apxs


注意上述命令中--enable-fpm的作用是开启php的fastcgi功能,即开启php-fpm功能。
--with-mysql=/usr/local/mysql是启用php支持mysql的功能,/usr/local/mysql是mysql数据库的安装路径。
--enable-mbstring表示启用mbstring模块mbstring模块的主要作用在于检测和转换编码,提供对应的多字节操作的字符串函数。目前php内部的编码只支持ISO-8859-*、EUC-JP、UTF-8,其他的编码的语言是没办法在php程序上正确显示的,所以我们要启用mbstring模块。
--with-iconv-dir=/usr/local指定php存放libiconv库的位置。
--with-apxs2=/usr/local/apache2/bin/apxs指定php查找apache的位置。
编译完毕后,我们再来make。在make时,我们注意要加上-liconv参数。如果不加上-liconv参数,系统在make编译会报错。报错信息如下:
Generating phar.php
php-5.3.16/sapi/cli/php: error while loading shared libraries: libiconv.so.2: cannot open shared object file: No such file or directory
使用命令如下:
make ZEND_EXTRA_LIBS='-liconv'
我们也可以通过修改Makefile文件,在ZEND_EXTRA_LIBS行加入-liconv。如下:

vi Makefile

make install

通过上图,我们可以很明显的看到apache配置文件httpd中启用php支持,同时也把libphp5.so文件复制到apache的模块目录下。
三、配置apache使其支持php
php安装完毕后,我们就可以通过修改apache的配置文件httpd.conf来使其支持php。
我们只需要在httpd.conf文件中加入如下两行代码:
LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php
注意,其中LoadModule php5_module modules/libphp5.so行,我们查看httpd.conf文件时会发现该行已经存在。那是因为在安装php时,添加的。现在我们只需要添加AddType application/x-httpd-php .php行即可。
vi /usr/local/apache2/conf/httpd.conf

除此之外,我们还需要修改apache的默认主页文件,添加index.php。内容如下:
echo "<?php phpinfo();?>">/usr/local/apache2/htdocs/index.php
cat /usr/local/apache2/htdocs/index.php


四、测试php
以上修改完毕后,我们重新启动apache,使用如下命令:
/etc/init.d/httpd graceful
注意该命令可以优雅的重启apache。

打开站点,如下:

通过上图,我们可以很明显的看到apache已经支持php。 |