您的位置:首页 > 运维架构 > Apache

web服务器apache理论、实践详解

2013-08-25 15:58 363 查看
一、tcp/ip协议

TCP标志位,有6种标示:SYN(synchronous建立联机) ,ACK(acknowledgement 确认) ,PSH(push传送),FIN(finish结束) ,RST(reset重置), URG(urgent紧急)
Sequence number(顺序号码) ,Acknowledge number(确认号码),在上面我们已经详细说明!下图是工作原理图:


三次握手:
第一次握手:建立连接时,主机A发送SYN包(syn=m)到服务器,并进入SYN_SEND状态,等待主机B确认
第二次握手:主机B收到SYN包,必须确认主机A的SYN(ACK=m+1),同时自己也发送一个SYN包(SYN=n),即SYN+ACK包,此时主机B进入SYN_RECV状态
第三次握手:主机A收到主机B的SYN+ACK包,向主机B发送确认包ACK(ACK=n+1),此包发送完毕,主机A和主机B进入ESTABLISHED状态,完成三次握手
四次断开:
当主机A完成数据传输后,将控制位FIN置1,提出停止TCP连接的请求
主机B收到FIN后对其作出响应,确认这一方向上的TCP连接将关闭,将ACK置1
由主机B端再提出反方向的关闭请求,将FIN置1
主机A对主机B的请求进行确认,将ACK置1,双方向的关闭结束
二、http请求模型和工作模式



上图是http的请求模式,http的工作模式有三种:prefork、worker、event,下面介绍prefork和worker的工作模式,prefork模式使用多个子进程,每个子进程只有一个线程。每个进程在某个确定的时间只能维持一个连接。在大多数平台上,Prefork MPM在效率上要比Worker MPM要高,但是内存使用大得多。prefork的无线程设计在某些情况下将比worker更有优势:它可以使用那些没有处理好线程安全的第三方模块,并且对于那些线程调试困难的平台而言,它也更容易调试一些。perfork模式原理图:




worker模式使用多个子进程,每个子进程有多个线程。每个线程在某个确定的时间只能维持一个连接。通常来说,在一个高流量的HTTP服务器 上,Worker MPM是个比较好的选择,因为Worker MPM的内存使用比Prefork MPM要低得多。但worker MPM也由不完善的地方,如果一个线程崩溃,整个进程就会连同其所有线程一起”死掉”.由于线程共享内存空间,所以一个程序在运行时必须被系统识别为”每 个线程都是安全的”。下面是worker的工作原理图:


总的来说,prefork方式速度要稍高于worker,然而它需要的cpu和memory资源也稍多于woker。
查看现使用的工作模式:
apachectl -l

三、http报文首部组成
http报文首部包括:包括请求首部和响应首部
一般都包括:起始行,首部:可以有多个,主体
request首部:

起始行:<method>请求方法 <request-URL>请求资源的路径 <version>使用http的版本
首部:<headers>可以有多个
请求的主体部分:<entity-body>
response首部:

起始行<version>协议版本号 <status>状态码 <reason-phrase>原因短语
首部:<headers>可以有多个
请求的主体部分:<entity-body>

[root@stu2~]# telnet 172.16.0.1 80
Trying172.16.0.1...
Connectedto 172.16.0.1.
Escapecharacter is '^]'.
#下面是请求首部
GET/centos6.repo http/1.1
Host:172.16.0.1
#下面是响应首部部分
HTTP/1.1200 OK
Date:Sat, 24 Aug 2013 03:06:48 GMT
Server:Apache/2.2.15 (CentOS)
Last-Modified:Sat, 17 Aug 2013 10:06:13 GMT
ETag:"20de6-12d-4e421db6ce2c1"
Accept-Ranges:bytes
Content-Length:301
Connection:close
Content-Type:text/plain; charset=UTF-8
#下面是响应主体部分
[base]
name=CentOS$releasever $basearch on local server 172.10.0.1
baseurl=http://172.16.0.1/cobbler/ks_mirror/centos-6.4-$basearch/
gpgcheck=0
[epel]
name=FedoraEPEL for CentOS$releasever $basearch on local server 172.16.0.1
baseurl=http://172.16.0.1/fedora-epel/$releasever/$basearch/
gpgcheck=0
Connectionclosed by foreign host.


web服务器软件httpd

[root@stu2~]# rpm -ql httpd #查看安装httpd软件包生成的列表
#下面是几个比较重要的
/etc/httpd#运行目录
/etc/httpd/conf/httpd.conf#主配置文件
/etc/httpd/conf.d/*.conf#扩展配置文件
/etc/rc.d/init.d/httpd#服务脚本
/var/www/cgi-bin# CGI脚本路径
/var/www/html#网页文件目录
启动httpd服务提供主页面进行验证:
[root@stu2~]# service httpd restart
Stoppinghttpd:                                           [  OK  ]
Startinghttpd:                                            [ OK  ]
提供默认主页面:index.html
#cd/var/www/html
#vimindex.html
<html>
<title>Test Page</title>
<boby>
<h1>Helloworld</h1>
<h2>Studyhard</h2>
</boby>
</html>




四、详解httpd的工作属性:
在主配置文件/etc/httpd/conf/httpd.conf中配置文件的构成:
[root@stu2conf]# grep "Section" httpd.conf
###Section 1: Global Environment #全局配置:对主服务器或虚拟机都有效,且有些功能是服务器自身工作属性;
###Section 2: 'Main' server configuration #对主服务器的配置
###Section 3: Virtual Hosts #对虚拟主机及属性定义
需要注意的是:指令不区分字符大小写,但约定俗成的习惯:单词的首字母使用大写;指令的值很有可能区分大小写;有些指令可以重使用多次; 而且要特别注意的是主服务器和虚拟主机不能同时启用
配置文件语法测试:
#service httpd configtest或者# httpd –t
大多数配置修改后,使用service httpd reload即能生效;而修改监听的地址和端口通常需要重启服务
1.配置监听的地址和端口
Listen[IP:]PORT
可以是http监听在不同的端口修改配置文件
Listen 80 #默认监听的端口
Listen172.16.2.1:8080 #新添加的监听的地址和端口



2、配置所选用的MPM的属性
[root@stu2conf]# httpd –l #查看核心模块
Compiledin modules:
core.c
prefork.c
http_core.c
mod_so.c
[root@stu2conf]# httpd  -t -D DUMP_MODULES #查看扩展模块,只列了一小部分
LoadedModules:
core_module (static)
mpm_prefork_module (static)
http_module (static)
so_module (static)
要想配置使用编译进不同MPM的httpd,编辑/etc/sysconfig/httpd配置文件,定义如下行:

[root@stu2conf]# vim /etc/sysconfig/httpd
#HTTPD=/usr/sbin/httpd.worker#将其改为启动项
[root@stu2conf]# service httpd restart
Stoppinghttpd:                                           [  OK  ]
Startinghttpd:                                           [  OK  ]
[root@stu2conf]# ps aux | grep httpd
root      3361 0.0  0.3 184360  4036 ?       Ss   13:41   0:00 /usr/sbin/httpd.worker
apache    3364 0.0  0.5 528620  5332 ?       Sl   13:41   0:00 /usr/sbin/httpd.worker
apache    3368 0.0  0.5 528620  5340 ?        Sl  13:41   0:00/usr/sbin/httpd.worker
apache    3369 0.0  0.5 528620  5332 ?       Sl   13:41   0:00 /usr/sbin/httpd.worker
root      3478 0.0  0.0 103244   832 pts/0   S+   13:41   0:00 grep httpd
3、配置服务器支持keep-alived

在配置文件/etc/httpd/conf/httpd.conf中将
KeepAliveOff改为KeepAlive On
KeepAliveTimeout15#定义保持连接的超时时间
MaxKeepAliveRequests100 #保持连接时的最大请求资源数量
4、配置站点根目录
#mkdir–pv /website/htdocs
#cd/website/htdocs
#touchtest.txt
编辑test.txt在里面写上test page然后修改配置文件
DocumentRoot"/website/htdocs"
#httpd–t
#servicehttpd restart



5、配置页面文件访问属性

<Directory"/website/htdocs">
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
Indexes: 是否允许索引页面文件,建议关闭;
FollowSynLinks: 是否跟随软链接文件;
ExecCGI:是否允许执行CGI脚本

6、访问控制
基于客户端访 Order:
定义allow和deny哪个为默认法则;写在后面的为默认法则:写在前面的指令没有显式定义的即受后面的指令控制
Order allow,deny
Deny from 172.16.100.177
Allowfrom 172.16.0.0/16表示允许172.16.0.0/16这个网段客户访问,但不允许172.16.100.177这个主机访问
7、定义默认主页面:
DirectoryIndex index.php index.jsp index.html8、路径别名
当前的根文件路径 DocumentRoot"/web/htdocs"
假如我们访问的路径为http://www.magedu.com/images/logo.gif 就相当于访问的路径为/web/htdocs/images/logo.gif,现在我们可以为images设置一个路径别名,这个别名可以完全不在/web/htdocs目录下,假如为/www/static则我们访问的资源相当于/www/static/logo.gif
#mkdir–pv /website/htdocs/images
#cd/website/htdocs/images/
#vimindex.html添加上/website/htdocs/images/index.html



然后修改配置文件在定义路径别名的区段添加上一行
Alias/images/ "/www/static/"
重新加载后进行访问:



9.脚本别名
在主配置文件中找到定义脚本别名的区域添加一行
ScriptAlias/cgi-bin/ "/website/cgi-bin/"
#mkdir–pv /website/cgi-bin/
#vim/website/cgi-bin/test.sh
#!/bin/bash
cat<< EOF
Content-Type:text/html
<pre>
Thehostname is:`/bin/hostname`
Thetime is:`date`
</pre>
EOF
#chmod+x /website/cgi-bin/test.sh
#bash–n /website/cgi-bin/test.sh
重新加载后进行访问



10、基于用户访问控制
首先建立用户帐号文件
htpasswd -c-m /path/to/password_file USERNAME
第一次添加用户需要使用-c选项,以后在创建用户密码不需要在加-c选项,否则会覆盖之前创建的用户
#touch/etc/httpd/conf/.htpass
[root@stu2~]# cat /etc/httpd/conf/.htpass
hailian:$apr1$3zZsobQO$VjmRke86PTKV1158/uStl/
centos:$apr1$Zye7Kzwy$hZNFUgPBBPNI4lm08bzsZ.
gentoo:$apr1$lFHVwghN$fyL5YpBJbFtdhzprJ/gn61
DocumentRoot"/website/htdocs/"
<Directory"/website/htdocs/downloads">
Options Indexes
AuthType Basic
AllowOverride AuthConfig
AuthName "Only for employee"
AuthUserFile /etc/httpd/conf/.htpass
Require valid-user
</Directory>
11、虚拟主机
注意的是虚拟主机和主服务器不能同时使用:关闭主服务器,注释主服务器的DocumentRoot即可;
启用NameVirtualHost 172.16.2.1:80
监听的端口添加一行Listen 8080
基于端口号的虚拟主机
基于ip的虚拟主机
基于主机名的虚拟主机
配置:
<VirtualHost172.16.2.1:80>
ServerName www.a.com
DocumentRoot "/web/host1"
CustomLog"/var/log/httpd/host1_access_log" combined
</VirtualHost>
<VirtualHost172.16.2.1:80>
ServerName www.b.org
DocumentRoot "/web/host2"
CustomLog"/var/log/httpd/host2_access_log" combined
<Directory"/web/host2">
Options None
AllowOverride AuthConfig
AuthName "Host2 is private."
AuthType Basic
AuthUserFile /etc/httpd/conf/.htpass
Require valid-user
</Directory>
</VirtualHost>
<VirtualHost172.16.10.8:80>
ServerName www.c.net
DocumentRoot "/web/host3"
CustomLog "/var/log/httpd/host3_access_log"combined
</VirtualHost>
<VirtualHost172.16.10.8:8080>
ServerName www.d.gov
DocumentRoot "/web/host4"
CustomLog"/var/log/httpd/host4_access_log" common
</VirtualHost>












12、httpd status
确保这个模块LoadModule status_module modules/mod_status.so是装载的,以为status这个功能是依赖于此模块的
<Location/status>#定义了访问status的URL路径,可以修改
SetHandlerserver-status#表示启动处理器,其名称是不能修改
</Location>



当然也可以将ExtendedStatus On开启,可以看到更为详细的服务器状态,没有需要时建议关闭
服务器的这些状态信息一般是不允许任何人随意查看的,因此可以定义其访问控制机制,默认是基于Ip的,也可以基于用户的,操作如下

<Location/status>
SetHandler server-status
#       AllowOverride AuthConfig #若不启动基于ip的这项不需要
AuthName "Status"
AuthType Basic
AuthUserFile/etc/httpd/conf/.statuspass
Require valid-user
#    Order deny,allow
#    Deny from all
#    Allow from .example.com



然后创建用户

[root@stu2conf]# touch .statuspass
[root@stu2conf]# htpasswd -c -m .statuspass status
Newpassword:
Re-type newpassword:
Addingpassword for user status


13.https的创建要想基于ssl回话,则需要装载一个ssl模块叫mod_ssl
[root@stu2conf]# yum install mod_ssl
[root@stu2conf]# rpm -ql mod_ssl
/etc/httpd/conf.d/ssl.conf#ssl.conf中定义了装载的模块,监听的端口,定义的默认虚拟主机等相关信息,是被我们的主配置文件所装载的
/usr/lib64/httpd/modules/mod_ssl.so#装载的mod_ssl.so模块
#下面是为ssl回话提供缓存机制的
/var/cache/mod_ssl
/var/cache/mod_ssl/scache.dir
/var/cache/mod_ssl/scache.pag
/var/cache/mod_ssl/scache.sem
[root@stu2conf]# ls -l /etc/httpd/
total 8
drwxr-xr-x.2 root root 4096 Aug 24 04:07 conf
drwxr-xr-x.2 root root 4096 Aug 24 04:08 conf.d
lrwxrwxrwx.1 root root   19 Aug 10 08:38 logs ->../../var/log/httpd
lrwxrwxrwx.1 root root   29 Aug 10 08:38 modules-> ../../usr/lib64/httpd/modules
lrwxrwxrwx.1 root root   19 Aug 10 08:38 run ->../../var/run/httpd
自建CA
[root@stu2CA]# cd private/
[root@stu2private]# (umask 077;openssl genrsa -out cakey.pem 2048)
GeneratingRSA private key, 2048 bit long modulus
...................+++
......+++
e is 65537(0x10001)
[root@stu2private]# cd ..
[root@stu2CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3656
You areabout to be asked to enter information that will be incorporated
into yourcertificate request.
What youare about to enter is what is called a Distinguished Name or a DN.
There arequite a few fields but you can leave some blank
For somefields there will be a default value,
If youenter '.', the field will be left blank.
-----
CountryName (2 letter code) [XX]:CN
State orProvince Name (full name) []:henan
LocalityName (eg, city) [Default City]:zhengzhou
OrganizationName (eg, company) [Default Company Ltd]:apachessl
OrganizationalUnit Name (eg, section) []:tech
Common Name(eg, your name or your server's hostname) []:www.magedu.com
EmailAddress []:
[root@stu2CA]# ls
cacert.pem  certs crl  newcerts  private
[root@stu2CA]# touch serial index.txt
[root@stu2CA]# echo 01 > serial
[root@stu2CA]# ls
cacert.pem  certs crl  index.txt  newcerts private  serial
[root@stu2 ssl]# (umask 077;openssl genrsa-out httpd.key 2048)
GeneratingRSA private key, 2048 bit long modulus
..........+++
.......................+++
eis 65537 (0x10001)
[root@stu2ssl]# openssl req -new -key httpd.key -out httpd.csr -days 3656
Youare about to be asked to enter information that will be incorporated
intoyour certificate request.
Whatyou are about to enter is what is called a Distinguished Name or a DN.
Thereare quite a few fields but you can leave some blank
Forsome fields there will be a default value,
Ifyou enter '.', the field will be left blank.
-----
CountryName (2 letter code) [XX]:CN
Stateor Province Name (full name) []:henan
LocalityName (eg, city) [Default City]:zhengzhou
OrganizationName (eg, company) [Default Company Ltd]:apachessl
OrganizationalUnit Name (eg, section) []:tech
CommonName (eg, your name or your server's hostname) []:www.hailian.com
EmailAddress []:
Pleaseenter the following 'extra' attributes
tobe sent with your certificate request
Achallenge password []:
Anoptional company name []:
[root@stu2ssl]# ls
httpd.csr  httpd.key
[root@stu2ssl]# openssl ca -in httpd.csr -out httpd.crt -days 3656
Usingconfiguration from /etc/pki/tls/openssl.cnf
Checkthat the request matches the signature
Signatureok
CertificateDetails:
Serial Number: 2 (0x2)
Validity
Not Before: Aug 23 20:54:06 2013GMT
Not After : Aug 27 20:54:06 2023 GMT
Subject:
countryName               = CN
stateOrProvinceName       = henan
organizationName          = apachessl
organizationalUnitName    = tech
commonName                = www.hailian.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
42:E4:0D:53:42:1C:E4:B3:9E:DE:87:4D:D7:46:D8:C3:EB:6B:32:4E
X509v3 Authority Key Identifier:
keyid:C7:08:F5:87:6E:E3:7E:AA:21:6F:0A:C2:42:07:3B:18:7A:B7:5F:55
Certificateis to be certified until Aug 27 20:54:06 2023 GMT (3656 days)
Signthe certificate? [y/n]:y
1out of 1 certificate requests certified, commit? [y/n]y
Writeout database with 1 new entries
DataBase Updated
修改ssl.conf配置文件
DocumentRoot"/web/host1"
ServerNamewww.hailian.com
SSLCertificateFile/etc/httpd/conf/ssl/httpd.crt
SSLCertificateKeyFile/etc/httpd/conf/ssl/httpd.key
修改httpd.conf文件
<VirtualHost172.16.2.1:80>
ServerName www.hailian.com
DocumentRoot "/web/host1"
CustomLog"/var/log/httpd/host1_access_log" combined
</VirtualHost>
[root@stu2conf]# openssl s_client -connect www.hailian.com:443 -CAfile/etc/pki/CA/cacet.pem #测试命令
#下面是结果的一部分
SSL-Session:
Protocol : TLSv1
Cipher   : DHE-RSA-AES256-SHA
Session-ID:F268D4B1566E7CE699A92A5C41896CADFB080D74FEB692F9C02F7D251CC8280F
Session-ID-ctx:
Master-Key:18C80412E148C25FC046F7592EE137A71156059E97F1238442ADCBC39D413B8A47EBCF4DBEBBD6075FF471149E129129


总结:内容较多,多加练习,熟练掌握,对以后的学习有很大的帮助,不足之处,多多提请!
本文出自 “时光的印记” 博客,请务必保留此出处http://lanlian.blog.51cto.com/6790106/1282358
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: