赵峰之城-我是做技术的,又没有坏心眼,发不了财,咋办?
前言  预习  配置详解  最近更新  关于 返回 返回中文centOS攻略首页

<用Apache构建HTTP服务器>(最近更新日:2006/08/26)

前  言

对于大多数的网络服务器,最广泛的功能就是开通HTTP服务,达到开放和发布网站的目的。目前绝大多数的网络交互程序,例如论坛、社区等等也是基于HTTP而建立的。

在这里,我们通过Web服务器软件中,使用量超过半数的自由软件Apache,来构建一台和我们看到的一般的网站具有相同功能的服务器,使它能够在我们发布网页的基础上,实现可以运行Perl、PHP的等等语言编写的交互程序,以及在虚拟主机、保密方面的功能的实现。

安装HTTP(Apache)服务器及相关组件

首先来安装Apache服务器及相关组件。这里使用yum命令来在线安装。

[root@sample~]#yum-yinstallhttpd ←在线安装httpd

SettingupInstallProcess
Settinguprepositories
dag100%|=========================|1.1kB00:00
update100%|=========================|951B00:00
base100%|=========================|1.1kB00:00
addons100%|=========================|951B00:00
extras100%|=========================|1.1kB00:00
Readingrepositorymetadatainfromlocalfiles
ReducingDagRPMRepositoryforRedHatEnterpriseLinuxtoincludedpackagesonly
Finished
Parsingpackageinstallarguments
ResolvingDependencies
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Downloadingheaderforhttpdtopackintotransactionset.
httpd-2.0.52-28.ent.cento100%|=========================|62kB00:00
--->Packagehttpd.i3860:2.0.52-28.ent.centos4settobeupdated
-->Runningtransactioncheck
-->ProcessingDependency:libaprutil-0.so.0forpackage:httpd
-->ProcessingDependency:apr>=0.9.4-24.2forpackage:httpd
-->ProcessingDependency:libapr-0.so.0forpackage:httpd
-->ProcessingDependency:httpd-suexecforpackage:httpd
-->RestartingDependencyResolutionwithnewchanges.
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Downloadingheaderforaprtopackintotransactionset.
apr-0.9.4-24.5.c4.1.i386.100%|=========================|7.5kB00:00
--->Packageapr.i3860:0.9.4-24.5.c4.1settobeupdated
--->Downloadingheaderforhttpd-suexectopackintotransactionset.
httpd-suexec-2.0.52-28.en100%|=========================|22kB00:00
--->Packagehttpd-suexec.i3860:2.0.52-28.ent.centos4settobeupdated
--->Downloadingheaderforapr-utiltopackintotransactionset.
apr-util-0.9.4-21.i386.rp100%|=========================|5.2kB00:00
--->Packageapr-util.i3860:0.9.4-21settobeupdated
-->Runningtransactioncheck

DependenciesResolved

=============================================================================
PackageArchVersionRepositorySize
=============================================================================
Installing:
httpdi3862.0.52-28.ent.centos4update888k
Installingfordependencies:
apri3860.9.4-24.5.c4.1base88k
apr-utili3860.9.4-21base51k
httpd-suexeci3862.0.52-28.ent.centos4update28k

TransactionSummary
=============================================================================
Install4Package(s)
Update0Package(s)
Remove0Package(s)
Totaldownloadsize:1.0M
DownloadingPackages:
(1/4):apr-0.9.4-24.5.c4.100%|=========================|88kB00:00
(2/4):httpd-suexec-2.0.5100%|=========================|28kB00:00
(3/4):httpd-2.0.52-28.en100%|=========================|888kB00:02
(4/4):apr-util-0.9.4-21.100%|=========================|51kB00:00
warning:rpmts_HdrFromFdno:V3DSAsignature:NOKEY,keyID443e1821
Publickeyforapr-0.9.4-24.5.c4.1.i386.rpmisnotinstalled
RetrievingGPGkeyfromhttp://mirror.centos.org/centos/RPM-GPG-KEY-centos4
ImportingGPGkey0x443E1821"CentOS-4key<centos-4key@centos.org>"
Keyimportedsuccessfully
RunningTransactionTest
FinishedTransactionTest
TransactionTestSucceeded
RunningTransaction
Installing:apr#########################[1/4]
Installing:apr-util#########################[2/4]
Installing:httpd#########################[3/4]
Installing:httpd-suexec#########################[4/4]

Installed:httpd.i3860:2.0.52-28.ent.centos4
DependencyInstalled:apr.i3860:0.9.4-24.5.c4.1apr-util.i3860:0.9.4-21httpd-suexec.i3860:2.0.52-28.ent.centos4
Complete!

为了使服务器开通HTTP服务后能够运行PHP编写的交互程序,接下来安装PHP。

[root@sample~]#yum-yinstallphp ←在线安装PHP

SettingupInstallProcess
Settinguprepositories
Readingrepositorymetadatainfromlocalfiles
ReducingDagRPMRepositoryforRedHatEnterpriseLinuxtoincludedpackagesonly
Finished
Parsingpackageinstallarguments
ResolvingDependencies
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Downloadingheaderforphptopackintotransactionset.
php-4.3.9-3.15.i386.rpm100%|=========================|23kB00:00
--->Packagephp.i3860:4.3.9-3.15settobeupdated
-->Runningtransactioncheck
-->ProcessingDependency:php-pearforpackage:php
-->RestartingDependencyResolutionwithnewchanges.
-->Populatingtransactionsetwithselectedpackages.Pleasewait.
--->Downloadingheaderforphp-peartopackintotransactionset.
php-pear-4.3.9-3.15.i386.100%|=========================|33kB00:00
--->Packagephp-pear.i3860:4.3.9-3.15settobeupdated
-->Runningtransactioncheck

DependenciesResolved

=============================================================================
PackageArchVersionRepositorySize
=============================================================================
Installing:
phpi3864.3.9-3.15update1.3M
Installingfordependencies:
php-peari3864.3.9-3.15update266k

TransactionSummary
=============================================================================
Install2Package(s)
Update0Package(s)
Remove0Package(s)
Totaldownloadsize:1.6M
DownloadingPackages:
(1/2):php-pear-4.3.9-3.1100%|=========================|266kB00:00
(2/2):php-4.3.9-3.15.i38100%|=========================|1.3MB00:01
RunningTransactionTest
FinishedTransactionTest
TransactionTestSucceeded
RunningTransaction
Installing:php#########################[1/2]
Installing:php-pear#########################[2/2]

Installed:php.i3860:4.3.9-3.15
DependencyInstalled:php-pear.i3860:4.3.9-3.15
Complete!

为了使PHP应用程序的执行效率大幅度提高,我们安装Zend。

[root@sample~]#wgethttp://downloads.zend.com/optimizer/3.0.1/ZendOptimizer-3.0.1-linux-glibc21-i386.tar.gz ←下载Zend的源代码

--13:19:06--http://downloads.zend.com/optimizer/3.0.1/ZendOptimizer-3.0.1-linux-glibc21-i386.tar.gz
=>`ZendOptimizer-3.0.1-linux-glibc21-i386.tar.gz'
Resolvingdownloads.zend.com...66.98.224.81
Connectingtodownloads.zend.com|66.98.224.81|:80...connected.
HTTPrequestsent,awaitingresponse...200OK
Length:6,358,090(6.1M)[application/gzip]

100%[====================================>]6,358,090240.53K/sETA00:00

13:19:33(238.15KB/s)-`ZendOptimizer-3.0.1-linux-glibc21-i386.tar.gz'saved[6358090/6358090]

[root@sample~]#
tarzxvfZendOptimizer-3.0.1-linux-glibc21-i386.tar.gz←展开被压缩的源代码

[root@sample~]#cdZendOptimizer*←进入Zend的源代码目录

[root@sampleZendOptimizer-3.0.1-linux-glibc21-i386]#./install.sh←运行安装脚本

然后会出现对话方式的安装向导,图样如下:

[1]选择OK,进入安装向导。



[2]阅读协议后,选择EXIT。



[3]选择Yes同意使用协议。



[4]设置安装目录,这里以默认的/usr/local/Zend为例,然后选择OK进入下一步。



[5]设置PHP配置文件所在的位置,一般为/etc(默认),如果PHP的配置文件在别处的话,请根据实际情况设置。



[6]被询问是否使用Apache服务器,这里选择Yes。



[7]设置Apache的路径,这里保持默认,选择OK进入下一步。



[8]选择OK进入下一步。



[9]然后开始安装…稍等片刻,安装完成后,提示安装成功,选择OK进入下一步。



[10]选择No,不重新启动HTTP服务(由于Apache也刚刚安装完毕,还没有被启动过。为了安全,等我们将Apache配置完毕后,再启动HTTP服务。)。然后会出现命令行--ZendOptimizer安装完毕。



[root@sampleZendOptimizer-3.0.1-linux-glibc21-i386]#cd ←回到root根目录

[root@sample~]#rm-rfZendOptimizer* ←删除安装后遗留的源文件及目录


配置HTTP(Apache)服务器

接下来,为了使服务器更安全以及更加符合我们的实际要求,对默认的设置进行一些必要的更改。尤其在一些细节方面,越少向外界透露服务器的信息,就越能保证服务器的安全。

[root@sample~]#vi/etc/httpd/conf/httpd.conf ←编辑Apache的配置文件

#
#Don'tgiveawaytoomuchinformationaboutallthesubcomponents
#wearerunning.Commentoutthislineifyoudon'tmindremotesites
#findingoutwhatmajoroptionalmodulesyouarerunning

ServerTokensOS ←找到这一行,将“OS”改为“Prod”(在出现错误页的时候不显示服务器操作系统的名称)

ServerTokensProd←变为此状态

#
#Optionallyaddalinecontainingtheserverversionandvirtualhost
#nametoserver-generatedpages(internalerrordocuments,FTPdirectory
#listings,mod_statusandmod_infooutputetc.,butnotCGIgenerated
#documentsorcustomerrordocuments).
#Setto"EMail"toalsoincludeamailto:linktotheServerAdmin.
#Settooneof:On|Off|EMail
#

ServerSignatureOn ←找到这一行,将“On”改为“Off”

ServerSignatureOff ←在错误页中不显示Apache的版本

#
#ServerAdmin:Youraddress,whereproblemswiththeservershouldbe
#e-mailed.Thisaddressappearsonsomeserver-generatedpages,such
#aserrordocuments.e.g.admin@your-domain.com
#

ServerAdminroot@localhost ←将管理员邮箱设置为自己常用的邮箱

ServerAdminyourname@yourserver.com ←根据实际情况修改默认设置

#
#ServerNamegivesthenameandportthattheserverusestoidentifyitself.
#Thiscanoftenbedeterminedautomatically,butwerecommendyouspecify
#itexplicitlytopreventproblemsduringstartup.
#
#IfthisisnotsettovalidDNSnameforyourhost,server-generated
#redirectionswillnotwork.SeealsotheUseCanonicalNamedirective.
#
#Ifyourhostdoesn'thavearegisteredDNSname,enteritsIPaddresshere.
#Youwillhavetoaccessitbyitsaddressanyway,andthiswillmake
#redirectionsworkinasensibleway.
#

#ServerNamenew.host.name:80 ←修改主机名

ServerNamewww.centospub.com:80 ←根据实际情况修改,端口号保持默认的80

#
#PossiblevaluesfortheOptionsdirectiveare"None","All",
#oranycombinationof:
#IndexesIncludesFollowSymLinksSymLinksifOwnerMatchExecCGIMultiViews
#
#Notethat"MultiViews"mustbenamed*explicitly*---"OptionsAll"
#doesn'tgiveittoyou.
#
#TheOptionsdirectiveisbothcomplicatedandimportant.Pleasesee
#http://httpd.apache.org/docs-2.0/mod/core.html#options
#formoreinformation.
#

OptionsIndexesFollowSymLinks ←找到这一行,删除“Indexes”,并添加“Includes”、“ExecCGI”

OptionsIncludesExecCGIFollowSymLinks ←允许服务器执行CGI及SSI

#
#AddHandlerallowsyoutomapcertainfileextensionsto"handlers":
#actionsunrelatedtofiletype.Thesecanbeeitherbuiltintotheserver
#oraddedwiththeActiondirective(seebelow)
#
#TouseCGIscriptsoutsideofScriptAliaseddirectories:
#(Youwillalsoneedtoadd"ExecCGI"tothe"Options"directive.)
#

#AddHandlercgi-script.cgi ←找到这一行,去掉行首的“#”,并在行尾添加“.pl”

AddHandlercgi-script.cgi.pl ←允许扩展名为.pl的CGI脚本运行

#
#AllowOverridecontrolswhatdirectivesmaybeplacedin.htaccessfiles.
#Itcanbe"All","None",oranycombinationofthekeywords:
#OptionsFileInfoAuthConfigLimit
#

AllowOverrideNone ←找到这一行,将“None”改为“All”

AllowOverrideAll ←变为此状态,允许.htaccess

#
#Thefollowingdirectivesdefinesomeformatnicknamesforusewith
#aCustomLogdirective(seebelow).
#

LogFormat"%h%l%u%t\"%r\"%>s%b\"%{Referer}i\"\"%{User-Agent}i\""combined ←找到这一行

LogFormat"%h%l%u%t\"%!414r\"%>s%b\"%{Referer}i\"\"%{User-Agent}i\""combined ←改为此状态(添加“!414”到规则中,对于过长的日志不记录)

#
#Specifyadefaultcharsetforallpagessentout.Thisis
#alwaysagoodideaandopensthedoorforfutureinternationalisation
#ofyourwebsite,shouldyoueverwantit.Specifyingitas
#adefaultdoeslittleharm;asthestandarddictatesthatapage
#isiniso-8859-1(latin1)unlessspecifiedotherwisei.e.you
#aremerelystatingtheobvious.Therearealsosomesecurity
#reasonsinbrowsers,relatedtojavascriptandURLparsing
#whichencourageyoutoalwayssetadefaultcharset.
#

AddDefaultCharsetUTF-8 ←找到这一行,在行首添加“#”

#AddDefaultCharsetUTF-8 ←不使用UTF-8作为网页的默认编码
AddDefaultCharsetGB2312 ←并接着添加这一行(添加GB2312为默认编码)

<Directory"/var/www/icons"> ←找到这一个标签,并在标签中更改相应选项
OptionsIndexesMultiViews ←找到这一行,将“Indexes”删除

OptionsMultiViews←变为此状态(不在浏览器上显示树状目录结构)
AllowOverrideNone
Orderallow,deny
Allowfromall
</Directory>


[root@sample~]#rm-f/etc/httpd/conf.d/welcome.conf/var/www/error/noindex.html ←删除测试页

启动HTTP服务

然后,启动HTTP服务。

[root@sample~]#chkconfighttpdon ←设置HTTP服务自启动

[root@sample~]#chkconfig--listhttpd
httpd0:off1:off2:on3:on4:on5:on6:off←确认2--5为on的状态就OK

[root@sample~]#/etc/rc.d/init.d/httpdstart ←启动HTTP服务
Startinghttpd:[OK] ←启动成功会出现OK
如果启动失败的话,会出现错误信息。原因可能是因为httpd.conf文件编辑过程中的失误,请检查httpd.conf。

然后,初步对HTTP服务进行简单测试。如下:

[root@sample~]#echohello>>/var/www/html/index.html ←建立测试页

然后,在下面输入服务器的IP地址,或域名(通过ifconfig命令可以看到IP地址;或者通过前面介绍过的“动态域名的申请”中的方法设置成功的域名来测试。)

WebSitePulse.com - free webmaster tools
Hostname:

如果成功的话会出现类似如下的页面:



然后,删除刚刚建立的测试页。

[root@sample~]#rm-f/var/www/html/index.html ←删除测试页

对HTTP服务进行全面测试

[1]对HTML格式网页正确显示的测试

[root@sample~]#vi/var/www/html/index.html ←建立测试页,内容如下:

<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=GB2312">
<title>Hello,World!</title>
<body>
Hello,World!
</body>
</html>

然后在浏览器中输入“http://服务器IP地址”或者“http://你的域名”,如果出现“Hello,World!”,并且浏览器读取编码为简体中文,就OK。

为了在这之后测试.htaccess,将默认为主页的index.html测试页删除。

[root@sample~]#rm-f/var/www/html/index.html ←删除刚刚测试用的网页

[2]对CGI的支持进行测试

[root@sample~]#vi/var/www/html/test.cgi ←建立CGI测试页,内容如下:

#!/usr/bin/perl
print"Content-Type:text/html\n\n";
print"<html><body>";
print"Hello,World!CGIisworking!<br>";
print"</body></html>";

[root@sample~]#chmod755/var/www/html/test.cgi←然后将CGI测试文件属性设置为755

然后在浏览器中输入“http://服务器IP地址/test.cgi”或者“http://你的域名/test.cgi”,如果正确显示“Hello,World!CGIisworking!”,说明对于CGI的支持没有问题。

[3]对PHP的支持进行测试

[root@samplehtml]#vi/var/www/html/test.php ←建立PHP测试文件,内容如下:

<?php
phpinfo();
?>

然后在浏览器中输入“http://服务器IP地址/test.php”或者“http://你的域名/test.php”后,正确的显示出了服务器上PHP的详细信息,说明对PHP可以正确的支持。


[4]对SSI进行测试

[root@sample~]#vi/var/www/html/test.shtml ←建立SSI测试页,内容如下:

<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=GB2312">
<title>Hello,World!</title>
<body>
TESTSSI
<!--#configtimefmt="%Y/%m/%d%H:%M:%S"-->
<!--#echovar="DATE_LOCAL"-->
</body>
</html>

然后在浏览器中输入“http://服务器IP地址/test.shtml”或者“http://你的域名/test.shtml”,如果正确显示当时的日期和时间,说明对于SSI的支持没有问题。

[5]对.htaccess的支持进行测试

[root@sample~]#vi/var/www/html/index.shtml ←建立.htaccess测试用的页,内容如下:

<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=GB2312">
<title>Hello,World!</title>
<body>
Thenameofthefileis<!--#echovar="DOCUMENT_NAME"-->
</body>
</html>

然后在浏览器中输入“http://服务器IP地址”或者“http://你的域名”,如果显示“Forbidden”,说明.htaccess正常。

然后建立一个.htaccess文件,并定义相应规则,如下:

[root@samplehtml]#vi/var/www/html/.htaccess ←建立.htaccess文件,内容如下:

DirectoryIndexindex.shtml

这时,再次在浏览器中输入“http://服务器IP地址”或者“http://你的域名”,如果正确显示“Thenameofthefileisindex.shtml”,说明.htaccess中的规则生效状态,OK。

[6]删除测试用的遗留文件

[root@samplehtml]#rm-f/var/www/html/*/var/www/html/.htaccess ←删除测试用过的遗留文件


<<<返回顶端