概述:

    本篇是http://1992tao.blog.51cto.com/11606804/1859597 的后续,将会继续介绍http-2.4的配置

===============================================================================

 11.日志设定

错误日志

ErrorLog Logs 定义格式及位置

  • 格式:ErrorLog "/PATH/TO/LOG_FILE" 

  • 位置:"/var/log/httpd/error_log"

LogLevel(日志错误级别,用来定义只记录哪些级别及高于次级别的相关事件)

  •  LogLevel warn 默认级别

wKioL1f6-tzwgN9fAABlQ4aUPRc223.png


访问日志

日志格式及名称定义方法:

  • LogFormat "FORMAT_STRINGS" LOG_FORMAT_NAME 

定义访问日志格式及名称:

  • CustomLog  "/PATH/TO/LOG_FILE"  LOG_FORMAT_NAME

wKioL1f6_2rSM1k6AADE7qYrXlc225.png


访问日志字符串格式如下:

wKioL1f7BlLgZXqyAACryPlNIFA409.png示例:

[root@centos7 httpd]# curl http://10.1.252.161/test.html
<html>
      <head>
           <title>Test Page</title>
      </head>
      <body>
           <h1>My Test Page</h1>
      </body>
</html>
# 假装是从百度跳转过来的
[root@centos7 httpd]# curl -e "http://www.baidu.com/search.html" http://10.1.252.161/test.html
<html>
      <head>
           <title>Test Page</title>
      </head>
      <body>
           <h1>My Test Page</h1>
      </body>
</html>

[root@centos7 httpd]# tail  /var/log/httpd/access_log
10.1.250.25 - - [10/Oct/2016:09:16:52 +0800] "GET /?C=D;O=A HTTP/1.1" 200 900 "http://10.1.252.161/?C=M;O=A" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"
10.1.250.25 - - [10/Oct/2016:09:16:54 +0800] "GET /?C=S;O=A HTTP/1.1" 200 900 "http://10.1.252.161/?C=D;O=A" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"
10.1.250.25 - - [10/Oct/2016:09:16:56 +0800] "GET /?C=N;O=A HTTP/1.1" 200 900 "http://10.1.252.161/?C=S;O=A" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"
10.1.252.161 - - [10/Oct/2016:10:59:19 +0800] "GET /test.html HTTP/1.1" 200 139 "-" "curl/7.29.0"
10.1.252.161 - - [10/Oct/2016:11:00:53 +0800] "GET /test.html HTTP/1.1" 200 139 "http://www.baidu.com/search.html" "curl/7.29.0"

 12.虚拟主机

虚拟主机:

  • 一个物理其可以有多个站点,每个站点可通过一个或者多个虚拟主机来实现;

httpd有三种类型的虚拟主机

  • 基于IP

  • 基于Port

  • 基于FQDN(ServerName)最有效的方法

定义虚拟主机的方法:

wKiom1i76jXx2trhAABAH0KqEn0751.png注意:

  • httpd-2.2要开启虚拟主机要首先关闭'Main' server 即中心主机,方法:注释DocumentRoot指令即可;并且如果基于ServerName的虚拟主机时,要使用专用配置指令:NameVirtualHost IP:PORT

  • httpd-2.4中不需要如上操作

  • 在全局配置的url在虚拟主机中也可以使用,比如manual和status,也可以单独定义url在不同的虚拟主机当中。

演示:

 1.首先创建目录,使每一个虚拟主机放置在一个单独的文件中,方便管理

# 使用for循环在vhosts目录中创建三个www{1,2,3}开头的目录,分别对应三台虚拟主机
[root@centos7 httpd]# for i in {1..3};do mkdir -pv /vhosts/www$i; echo "www$i : site $i" > /vhosts/www$i/index.html;done
mkdir: created directory ‘/vhosts’
mkdir: created directory ‘/vhosts/www1’
mkdir: created directory ‘/vhosts/www2’
mkdir: created directory ‘/vhosts/www3’
[root@centos7 httpd]# tree /vhosts/
/vhosts/
├── www1
│   └── index.html
├── www2
│   └── index.html
└── www3
    └── index.html

3 directories, 3 files

[root@centos7 httpd]# cat /vhosts/www1/index.html /vhosts/www2/index.html /vhosts/www3/index.html 
www1 : site 1
www2 : site 2
www3 : site 3

2.编辑配置文件,在/etc/httpd/conf.d/下添加一个以vhosts.conf文件表示虚拟主机文件 

1)基于port区分

# 编辑配置文件,在/etc/httpd/conf.d/下添加一个以vhosts.conf文件表示虚拟主机文件
[root@centos7 httpd]# vim conf.d/vhosts.conf 
# 编辑内容如下:因为是基于port所以,IP相同,端口不同
  1 <VirtualHost 10.1.252.161:80>
  2         ServerName www1.taotao.com
  3         DocumentRoot "/vhosts/www1"
  4         <Directory "/vhosts/www1">
  5              Options None
  6              AllowOverride None
  7              Require all granted
  8         </Directory>
  9 </VirtualHost>
 10 
 11 <VirtualHost 10.1.252.161:8080>
 12         ServerName www2.taotao.com
 13         DocumentRoot "/vhosts/www2"
 14         <Directory "/vhosts/www2">
 15              Options None
 16              AllowOverride None
 17              Require all granted
 18         </Directory>
 19 </VirtualHost>
 
[root@centos7 httpd]# httpd -t # 检查与语法错误
Syntax OK
[root@centos7 httpd]# systemctl reload httpd # 重载

 在浏览器中访问如下:

wKioL1f7J3WytQNcAAA_i8zE2Lk229.png

wKiom1f7J3XQMWTwAABElajEnIY900.png

2)合IP和Port(www1和www3是基于ip的,端口相同,ip不同)

# 首先添加一个IP地址,确保能ping通
[root@centos7 httpd]# ip addr add 10.1.252.73/16 dev eno16777736 # 添加ip地址
[root@centos7 httpd]# ip addr list # 查看所有ip
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eno16777736: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:d7:41:ed brd ff:ff:ff:ff:ff:ff
    inet 10.1.252.161/16 brd 10.1.255.255 scope global dynamic eno16777736
       valid_lft 66764sec preferred_lft 66764sec
    inet 10.1.252.73/16 scope global secondary eno16777736 # 添加的ip地址
       valid_lft forever preferred_lft forever

[root@centos7 httpd]# ping 10.1.252.73 # 可以ping通
PING 10.1.252.73 (10.1.252.73) 56(84) bytes of data.
64 bytes from 10.1.252.73: icmp_seq=1 ttl=64 time=0.029 ms

# 编辑虚拟主机的配置文件如下: 
[root@centos7 httpd]# vim conf.d/vhosts.conf 
  1 <VirtualHost 10.1.252.161:80>
  2         ServerName www1.taotao.com
  3         DocumentRoot "/vhosts/www1"
  4         <Directory "/vhosts/www1">
  5              Options None
  6              AllowOverride None
  7              Require all granted
  8         </Directory>
  9 </VirtualHost>
  
  11 <VirtualHost 10.1.252.161:8080>
 12         ServerName www2.taotao.com
 13         DocumentRoot "/vhosts/www2"
 14         <Directory "/vhosts/www2">
 15              Options None
 16              AllowOverride None
 17              Require all granted
 18         </Directory>
 19 </VirtualHost>
  
  <VirtualHost 10.1.252.73:80>
 22         ServerName www3.taotao.com
 23         DocumentRoot "/vhosts/www3"
 24         <Directory "/vhosts/www3">
 25              Options None
 26              AllowOverride None
 27              Require all granted
 28         </Directory>
 29 </VirtualHost>
 
 [root@centos7 httpd]# httpd -t
Syntax OK
[root@centos7 httpd]# !sys
systemctl reload httpd

  在浏览器中访问如下

wKioL1f7M7aQ3i6OAAA_nH4QIqQ611.png

wKiom1f7M7ey-NjhAAA39c2ZxA8781.png

wKioL1f7NIThBdmbAABBPLYLe7I138.png

3)基于主机名(主机名ServerName不同,IP和Port都相同)

 [root@centos7 httpd]# vim conf.d/vhosts.conf
  1 <VirtualHost *:80>
  2         ServerName www1.taotao.com
  3         DocumentRoot "/vhosts/www1"
  4         <Directory "/vhosts/www1">
  5              Options None
  6              AllowOverride None
  7              Require all granted
  8         </Directory>
  9 </VirtualHost>
 10 
 11 <VirtualHost *:80>
 12         ServerName www2.taotao.com
 13         DocumentRoot "/vhosts/www2"
 14         <Directory "/vhosts/www2">
 15              Options None
 16              AllowOverride None
 17              Require all granted
 18         </Directory>
 19 </VirtualHost>
 20 
 21 <VirtualHost *:80>
 22         ServerName www3.taotao.com
 23         DocumentRoot "/vhosts/www3"
 24         <Directory "/vhosts/www3">
 25              Options None
 26              AllowOverride None
 27              Require all granted
 28         </Directory>
"conf.d/vhosts.conf" 29L, 611C written                                                                                                               

[root@centos7 httpd]# httpd -t
Syntax OK
[root@centos7 httpd]# systemctl reload httpd

 我们要想访问不同的站点,就需要解析出这三个地址都到本机的地址上面来,这里编辑本地的/etc/hosts文件,完成解析

[root@centos7 httpd]# vim /etc/hosts
  1 
  2 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
  3 ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
  4 10.1.252.161 www1.taotao.com www2.taotao.com www3.taotao.com

 使用curl文本浏览器来测试如下:

[root@centos7 httpd]# curl http://www1.taotao.com
www1 : site 1
[root@centos7 httpd]# curl http://www2.taotao.com
www2 : site 2
[root@centos7 httpd]# curl http://www3.taotao.com
www3 : site 3

 13.基于用户和组的访问控制

访问控制方法:

  • Require user  USERLIST(用户名) 

  • Require group GRPLIST(组名)

http协议的认证方式

  • basic基本认证 

  • digest摘要认证

http协议认证过程:

认证质询

  • WW-Authencate:响应码为401,拒绝客户端请求,并说明用户需要输入正确的账号和密码之后方可访问;

认证:

  • Authorization:客户端填入账号和密码,再次发送请求报文;认证通过,服务器发送响应内容;

basic认证机制的实现

基于用户的认证

1)定义安全域

wKiom1i78zDzxGJ2AAA5PDyxXsw309.png

2)提供用户的账号文件

htpasswd 命令用于维护此文件

格式:

  • htpasswd [options] "/PATH/TO/HT_PASSWD_FILE" username

选项:

  • -c:添加第一个用户时创建此文件;

  • -m:以md5格式加密用户密码存放;

  •  -s:以sha格式加密用户密码存放;

  • -D:删除指定用户 

Require 使用方式

Require valid-user:

  • 所有位于AuthUserFile文件中定义的用户都允许登录;

Require user USER1 USER2:

  • 仅允许user1,user2等出现在AuthUserFile文件中定义的特定几个用户登录,这些用户为虚拟用户,即非系统用户;

基于组认证

1)定义安全域

wKioL1i78-WjttMrAAAzbC_gBao294.png

2)提供用户的账号文件

  • 每行定义一个组:group_name: user1 user2 ...

演示:

1.基于用户认证

 1)创建用户账号文件,并添加用户

[root@centos7 httpd]# htpasswd -c -m /etc/httpd/conf/.htpasswd tao 
New password: 
Re-type new password: 
Adding password for user tao

# 只有创建第一个用户时才使用 -c
[root@centos7 httpd]# htpasswd  -m /etc/httpd/conf/.htpasswd xiu 
New password: 
Re-type new password: 
Adding password for user xiu

# 查看文件如下:
[root@centos7 httpd]# cat /etc/httpd/conf/.htpasswd 
tao:$apr1$KYDxvZxS$VaQ0DVSvlJZlwuNFKUjR90
xiu:$apr1$oc3jfZq0$Fy4OyNCjFGYFmDRlH4mP8.

  2)为了演示效果创建一个目录

[root@centos7 conf.d]# mkdir /vhosts/www1/admin
[root@centos7 conf.d]# vim  /vhosts/www1/admin/admin.html
  1 <h1>TAOTAO XIUXIU</h1>

  3)编辑之前的虚拟主机配置文件,添加安全域

 [root@centos7 conf.d]# vim vhosts.conf
  1 <VirtualHost *:80>
  2         ServerName www1.taotao.com
  3         DocumentRoot "/vhosts/www1"
  4         <Directory "/vhosts/www1">
  5              Options None
  6              AllowOverride None
  7              Require all granted
  8         </Directory>
  9   # 添加安全域
 10         <Directory "/vhosts/www1/admin">
 11              Options None
 12              AllowOverride None
 13              AuthType Basic
 14              AuthName "Admin Area,Enter your name/pass"
 15              AuthUserFile "/etc/httpd/conf/.htpasswd"
 16              Require valid-user
 17          </Directory>
 18          ErrorLog "logs/www1-error_log"
 19          CustomLog "logs/www1-access_log" combined
 20 </VirtualHost>
[root@centos7 httpd]# httpd -t
Syntax OK
[root@centos7 httpd]# !sys
systemctl reload httpd

 通过浏览器访问如下:

wKiom1f7VIHSmRFQAABp8fBKV6Y055.png

wKioL1f7VIGzPiopAABNBDy-E-A782.png

2.基于组认证演示:

  1)在上例的基础上再创建两个用户,归为一个组里

# 在原来的基础上在添加两个用户tom和wang
[root@centos7 httpd]# htpasswd  -m /etc/httpd/conf/.htpasswd tom
New password: 
Re-type new password: 
Adding password for user tom

[root@centos7 httpd]# htpasswd  -m /etc/httpd/conf/.htpasswd wang
New password: 
Re-type new password: 
Adding password for user wang

[root@centos7 httpd]# cat /etc/httpd/conf/.htpasswd 
tao:$apr1$KYDxvZxS$VaQ0DVSvlJZlwuNFKUjR90
xiu:$apr1$oc3jfZq0$Fy4OyNCjFGYFmDRlH4mP8.
tom:$apr1$/AOJinXS$Zj.J1eWV/O9lEFn.4hdub1
wang:$apr1$YBD7fQtq$AbG8Gota3tUnFKwYX4bKd0

 2)创建组文件

[root@centos7 httpd]# vim conf/.htgroup
 admins:tom wang

 3)修改虚拟主机配置文件

  1 <VirtualHost *:80>
  2         ServerName www1.taotao.com
  3         DocumentRoot "/vhosts/www1"
  4         <Directory "/vhosts/www1">
  5              Options None
  6              AllowOverride None
  7              Require all granted
  8         </Directory>
  9 
 10         <Directory "/vhosts/www1/admin">
 11              Options None
 12              AllowOverride None
 13              AuthType Basic
 14              AuthName "Admin Area,Enter your name/pass"
 15              AuthUserFile "/etc/httpd/conf/.htpasswd"
 16              AuthgroupFile "/etc/httpd/conf/.htgroup"
 17              Require group admins
 18          </Directory>
 19          ErrorLog "logs/www1-error_log"
 20          CustomLog "logs/www1-access_log" combined
 21 </VirtualHost>
 
[root@centos7 httpd]# httpd -t
Syntax OK
[root@centos7 httpd]# systemctl reload httpd

 通过浏览器访问如下:

wKiom1f7WvWgy7jiAAB8coV-ANE302.png


综上所述:

  在基于主机名的虚拟主机中定义访问控制,基于用户组的访问控制,有自己独立的日志系统,定义路径别名,如下:

wKioL1f9sfPwY_hPAADDa4OLsvg950.png

http协议首部

 1.事务:request/response

事务

wKioL1i8A17BfxahAAAsFkhvEH8622.png

 如图所示为百度的调试界面:

wKioL1f7fN2htbG-AACVA_TkLKM185.png


 2.首部(headers)分类

分类:

  • 通用首部

  • 请求首部

  • 响应首部

  • 实体首部

  • 扩展首部

通用首部 

  • Connection:{close|keep-alive}表示:连接后立即断开或者保持连接

            一般而言,现在的浏览器在请求时一般都是keep-alive,而响应报文则取决于服务器端的配置是否启用了保持连接的功能来决定;

  • Date:报文创建的日期时间;

  • Via:显示报文中经过的中间节点;

  • Cache-Control:缓存控制;

  • Pragma:

请求首部 

  • Host:请求的服务器名称和端口号;

  • Referer:跳转至当前页面的上级资源; 

  • User-Agent:用户代理;

  • Client-IP:

Accept:可接收的MIME类型;

  • Accept-Language:可接收的语言

  • Accept-Encoding:所能够接收的编码格式,如gzip, defalte, 

  • Accept-Charset:所能接受的字符集

     ...

条件式请求首部(缓存相关):

  • Except:

  • If-Modified-Since:自从指定的时间之后,请求的资源是否发生过修改;

  • If-Unmodified-Since:

  • If-None-Match :本地缓存中存储的文档的ETag标签是否与服务器文档的ETag不匹配;

  • If-Match:

安全相关的请求首部:

  • Authorization:向服务器发送认证信息,请求授权,如账号和密码

  • Cookie:客户端向服务器发送cookie

  • Cookie2

如下图所示为百度的request报文:

wKioL1f7g6rw4Vr5AACP4R845yo719.png


响应首部 

信息性首部:

  • Age:响应持续时长

  • Server:服务器程序的名称和版本(建议隐藏)

协商类首部:

  • Accept-Range:服务器端可接受的请求类型范围

  • Vary:其它首部列表

安全相关的首部:

  • WWW-Authenticate:认证质询,来自服务器的对客户端的质询认证表单;

  • Set-Cookie:向客户端设置cookie

  • Set-Cookie2:

说明:

cookie (储存在用户本地终端上的数据)

  • 指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密)

  • Cookie就是服务器暂存放在你计算机上的一笔资料,好让服务器用来辨认你的计算机。当你在浏网站的时候,Web服务器会先送一小小资料放在你的计算机上,Cookie 会帮你在网站上所打的文或是一些选择,都记录下来。当下次你再光临同一个网站,Web服务器会先看看有没有它上次留下Cookie资料,有的话,就会依据Cookie里的内容来判断使用者,送出特定的网页内容给你。

 session

  • Session 是用于保持状态的基于 Web服务器的方法。Session 允许通过将对象存储在Web服务器的内存中,在整个用户会话过程中保持任何对象。

如下图所示为百度的response报文

wKiom1f7j9ax6MvSAACsH8SQU-A515.png

实体首部 

  • Content-Encoding:内容编码;明文还是压缩的;

  • Content-Language:内容语言;

  • Content-Lenth:主体长度;

  • Content-Location:实体真正所处位置

  • Content-Type :主题的对象类型

     ...

  • Allow:列出对此实体可使用的请求方法;

  • Location:告诉客户端真正的实体位于何处

缓存相关:

  • Etag:实体的扩展标签

  • Last-Modified:最后一次修改时间

  • Expires:实体的过期时间

扩展首部 

  • X-Forwarded-For:为谁转发,标记访问的客户端主机是谁

   ...

 3.url:Uniform Resource Locator

常用格式

  • scheme://host:port/path<协议>://<主机名称或地址>[:port]/<URL>

完整格式:

  • scheme://[<user>[:<password>]@<host>[:<port>]/<path>;<params>?<query>#frag

说明:

  • scheme:协议

  • params:参数, ;param1=value1&param2=value2

  • query:查询字符串, ?field1=value1&field2=value2

  • frag:页面锚定,#frag_id, 例如#ch1

 4.文本浏览器:curl和elinks

curl

介绍

  • curl是基于URL语法在命令行方式下工作的文件传输工具,它支持FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE及LDAP等协议。curl支持HTTPS认证,并且支持HTTP的POST、PUT等方法, FTP上传, kerberos认证,HTTP上传,代理服务器, cookies, 用户名/密码认证, 下载文件断点续传,上载文件断点续传, http代理服务器管道( proxy tunneling), 甚至它还支持IPv6, socks5代理服务器,,通过http代理服务器上传文件到FTP服务器等等,功能十分强大。

语法格式:

  • curl  [options]  [URL...]

选项

  • -A/--user-agent <string>:设置用户代理发送给服务器

  • --basic:使用HTTP基本认证

  • -e/--referer <URL>:来源网址

  • --cacert <file> :CA证书 (SSL)

  • --compressed :要求返回是压缩的格式

  • -H/--header <line>:自定义首部信息传递给服务器

  • -I/--head :只显示响应报文首部信息

  • --limit-rate <rate> :设置传输速度

    -u/--user <user[:password]>:设置服务器的用户和密码

  • -0/--http1.0 :使用HTTP 1.0

  • -X, --request <command>:自定义请求方法

elinks

用法:

  • elinks  [OPTION]... [URL]...

选项

  • -dump:不进入交互式模式,而直接将URL的内容输出至标准输出;

httpd-2.4基础配置

 1.使用mod_deflate模块压缩页面优化传输速度

适用场景

  • 节约带宽,额外消耗CPU;同时,可能有些较老浏览器不支持;

  • 压缩适于压缩的资源,例如文件文件

注意:

  • 不是所有的资源类型都适合压缩,适合压缩的文件是那些纯文本文件;

  • 设置输出过滤器(发送给响应报文用到的),过滤出来的执行压缩

演示:

 1.首先确保该模块已经安装,才可以启用模块

[root@centos7 ~]# httpd -M |grep deflate
 deflate_module (shared)

 2.复制一个大文件查看一下是否有deflate压缩机制

# 注意这里如果复制的文件其他用户没有权限要给他读权限,否则apache用户不能访问
[root@centos7 httpd]# cp /var/log/lastlog /var/www/html/lastlog.txt 

# 获取首部信息 
[root@centos7 httpd]# curl -I http://10.1.252.161/lastlog.txt  
HTTP/1.1 200 OK
Date: Mon, 10 Oct 2016 14:10:26 GMT
Server: Apache/2.4.6 (CentOS)
Last-Modified: Mon, 10 Oct 2016 14:08:17 GMT
ETag: "8eef4-53e834aa771bb"
Accept-Ranges: bytes
Content-Length: 585460
Content-Type: text/plain; charset=UTF-8 # 为文本信息,是支持压缩的

# 要求首部返回压缩格式
[root@centos7 httpd]# curl --compress -I http://10.1.252.161/lastlog.txt    
HTTP/1.1 200 OK
Date: Mon, 10 Oct 2016 14:10:55 GMT
Server: Apache/2.4.6 (CentOS)
Last-Modified: Mon, 10 Oct 2016 14:08:17 GMT
ETag: "8eef4-53e834aa771bb"
Accept-Ranges: bytes
Content-Length: 585460
Content-Type: text/plain; charset=UTF-8
# 此时后不支持压缩功能

 3.启动压缩模块配置,但是在压缩之前要先过滤,把适合压缩的文本文件过滤出来

# 创建文件 /etc/httpd/conf.d/deflate.conf
[root@centos7 httpd]# vim conf.d/deflate.conf
  1 SetOutputFilter DEFLATE  # 设置输出过滤器(发送给响应报文用到的),过滤出来的执行压缩
  2 # mod_deflate configuration      
  3                                  
  4 # Restrict compression to these MIME types
  5                                  
  6 # Restrict compression to these MIME types
  7 AddOutputFilterByType DEFLATE text/plain
  8 AddOutputFilterByType DEFLATE text/html
  9 AddOutputFilterByType DEFLATE application/xhtml+xml
 10 AddOutputFilterByType DEFLATE text/xml
 11 AddOutputFilterByType DEFLATE application/xml
 12 AddOutputFilterByType DEFLATE application/x-javascript
 13 AddOutputFilterByType DEFLATE text/javascript    
 14 AddOutputFilterByType DEFLATE text/css           
 15                                                  
 16 # Level of compression (Highest 9 - Lowest 1) 压缩级别                   
 17 DeflateCompressionLevel 9                                                
 18                                                                          
 19  # Netscape 4.x has some problems.  有些老的浏览器不支持压缩功能,要关闭掉
 20  BrowserMatch ^Mozilla/4  gzip-only-text/html
 21                                                                                                                          
 22 # Netscape 4.06-4.08 have some more problems   
 23 BrowserMatch  ^Mozilla/4\.0[678]  no-gzip      
 24                                                
 25  # MSIE masquerades as Netscape, but it is fine
 26 BrowserMatch \bMSI[E]  !no-gzip !gzip-only-text/html
 27 
~                                                                                                                                                                      
"conf.d/deflate.conf" [New] 27L, 973C written                                                                                                        
[root@centos7 httpd]# httpd -t
Syntax OK
[root@centos7 httpd]# !sys
systemctl reload httpd

  再次查看之前的文件

[root@centos7 httpd]# curl -I http://10.1.252.161/lastlog.txt
HTTP/1.1 200 OK
Date: Mon, 10 Oct 2016 14:35:05 GMT
Server: Apache/2.4.6 (CentOS)
Last-Modified: Mon, 10 Oct 2016 14:08:17 GMT
ETag: "8eef4-53e834aa771bb"
Accept-Ranges: bytes
Content-Length: 585460
Vary: Accept-Encoding  # 支持压缩机制
Content-Type: text/plain; charset=UTF-8

[root@centos7 httpd]# curl --compress -I http://10.1.252.161/lastlog.txt
HTTP/1.1 200 OK
Date: Mon, 10 Oct 2016 14:35:54 GMT
Server: Apache/2.4.6 (CentOS)
Last-Modified: Mon, 10 Oct 2016 14:08:17 GMT
ETag: "8eef4-53e834aa771bb-gzip"
Accept-Ranges: bytes
Vary: Accept-Encoding #接受编码
Content-Encoding: gzip # gzip 压缩
Content-Length: 685
Content-Type: text/plain; charset=UTF-8

https协议配置

 1.介绍

https:

  • http over ssl = https ,其对应的tcp协议的443端口,通过https://进行访问;

OpenSSL:

  • libcrpyto,

  • libssl (ssl/tls)

  • openssl

PKI

  • CA

SSL会话的简化过程 

wKiom1i8FbfSDafMAAC_rkcdWvg814.png注意:

  • SSL会话是基于IP地址创建;所以单IP的主机上,仅可以使用一个https虚拟主机;

 2.配置httpd支持https

步骤如下:

1)为服务器申请数字证书;

  测试通过私建CA发证书

  • 创建私有CA

  • 在服务器创建证书签署请求

  • CA签证

2)配置httpd支持使用ssl,及使用的证书;

  • # yum -y install mod_ssl

配置文件:/etc/httpd/conf.d/ssl.conf

      DocumentRoot

      ServerName

      SSLCertificateFile

      SSLCertificateKeyFile

3)测试基于https访问相应的主机;

  • # openssl  s_client  [-connect host:port] [-cert filename] [-CApath directory] [-CAfile filename]

演示

1.为了测试,首先在自己的主机上创建私有CA,但是在互联网上公开使用时,一定要找公共CA去签署

  1)生成私钥文件 

# 在/etc/pki/CA 下创建
[root@centos7 ~]# cd /etc/pki/CA 
[root@centos7 CA]# ls
certs  crl  newcerts  private
[root@centos7 CA]# ls private/

# 生成CA指定文件所在位置,和密钥长度
[root@centos7 CA]# (umask 077;openssl genrsa -out private/cakey.pem 4096) 
Generating RSA private key, 4096 bit long modulus
.........................................................++
........................................................................................++
e is 65537 (0x10001)

[root@centos7 CA]# ll private/  # 验证文件及权限
total 4
-rw------- 1 root root 3247 Oct 11 10:49 cakey.pem

 2)生成自签证书

[root@centos7 CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Beijing
Locality Name (eg, city) [Default City]:Beijing
Organization Name (eg, company) [Default Company Ltd]:MageEdu
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:ca.magedu.com
Email Address []:camaster@magedu.com

[root@centos7 CA]# ls
cacert.pem # 生成的自签证书 certs  crl  newcerts  private

 3)为CA提供目录和文件

[root@centos7 CA]# echo 01 > serial
[root@centos7 CA]# touch index.txt
[root@centos7 CA]# ls
cacert.pem  certs  crl  index.txt  newcerts  private  serial

 2.如上,创建CA完成,接下来要为httpd服务器签署CA请求

  1)创建用于httpd通信时的私钥

[root@centos7 CA]# cd /etc/httpd # 进到httpd目录中去
[root@centos7 httpd]# ls
conf  conf.d  conf.modules.d  logs  modules  run

[root@centos7 httpd]# mkdir ssl # 创建一个ssl目录

# 在ssl目录中创建一个私钥文件
[root@centos7 httpd]# cd ssl  
[root@centos7 ssl]# ls  
[root@centos7 ssl]# (umask 077;openssl genrsa -out httpd.key 2048)
Generating RSA private key, 2048 bit long modulus
...+++
.......................................+++
e is 65537 (0x10001)

[root@centos7 ssl]# ls
httpd.key # 创建成功

 2)利用生成的私钥生成证书签署请求:

[root@centos7 ssl]# openssl req -new -key httpd.key -out http.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN  
State or Province Name (full name) []:Beijing
Locality Name (eg, city) [Default City]:Beijing
Organization Name (eg, company) [Default Company Ltd]:MageEdu
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:www.magedu.com         #这里要签署的名字一定要和服务器主机名保持一致,这样用户用你网站的主机名访问你的站点时,才可以认证 
Email Address []:webmaster@magedu.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@centos7 ssl]# ls
http.csr  httpd.key

3.接下来CA要为httpd签发证书(因为这里都是在本地主机生成的CA和httpd服务,所以不需要传送)

[root@centos7 ssl]# openssl ca -in http.csr -out /etc/pki/CA/certs/httpd.crt
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 11 03:36:06 2016 GMT
            Not After : Oct 11 03:36:06 2017 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = Beijing
            organizationName          = MageEdu
            organizationalUnitName    = ops
            commonName                = www.magedu.com
            emailAddress              = webmaster@magedu.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                82:AB:2D:F0:C1:5F:E4:14:0C:A5:EC:4F:FB:E2:45:89:BF:14:00:7A
            X509v3 Authority Key Identifier: 
                keyid:95:98:49:F9:39:61:3A:15:5D:70:AA:71:CC:64:6C:E3:8E:C7:79:9A

Certificate is to be certified until Oct 11 03:36:06 2017 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

[root@centos7 ssl]# tree /etc/pki/CA/
/etc/pki/CA/
├── cacert.pem
├── certs
│   └── httpd.crt # 签署的证书
├── crl
├── index.txt
├── index.txt.attr
├── index.txt.old
├── newcerts
│   └── 01.pem
├── private
│   └── cakey.pem
├── serial
└── serial.old

 4.因为httpd默认没有ssl的模块,centos维护者单独把此模块做成了rpm包,所以需要额外安装,如下:

[root@centos7 ~]# httpd -M |grep ssl # 不存在
[root@centos7 ~]# yum install mod_ssl -y # 安装此模块
[root@centos7 ~]# rpm -ql mod_ssl
/etc/httpd/conf.d/ssl.conf
/etc/httpd/conf.modules.d/00-ssl.conf
/usr/lib64/httpd/modules/mod_ssl.so
/usr/libexec/httpd-ssl-pass-dialog
/var/cache/httpd/ssl
[root@centos7 ~]# httpd -M |grep ssl # 模块存在
 ssl_module (shared)

5.安装完成之后编辑此ssl的虚拟主机,修改对应的主机名,证书和私钥所在位置

[root@centos7 conf.d]# pwd
/etc/httpd/conf.d
[root@centos7 conf.d]# ls
autoindex.conf  deflate.conf  keepalive.conf  manual.conf  README  ssl.conf  status.conf  userdir.conf  vhosts.conf.bak  welcome.conf.bak

[root@centos7 conf.d]# cp ssl.conf{,.bak} # 首先备份
[root@centos7 conf.d]# ls
autoindex.conf  deflate.conf  keepalive.conf  manual.conf  README  ssl.conf  ssl.conf.bak  status.conf  userdir.conf  vhosts.conf.bak  welcome.conf.bak

[root@centos7 conf.d]# vim ssl.conf # 编辑文件
  <VirtualHost _default_:443>
   DocumentRoot "/var/www/html"  # 因为在主配置文件中已经做过授权了,所以不需授权,如果修改路径的话,就要授权
   
   #修改成对应的主机名
   ServerName www.magedu.com    
    #   SSL Engine Switch:
    #   Enable/Disable SSL for this virtual host.
    SSLEngine on  # 表示ssl协议是否启用
    
    #   Server Certificate:
    # Point SSLCertificateFile at a PEM encoded certificate.  If
    # the certificate is encrypted, then you will be prompted for a
    # pass phrase.  Note that a kill -HUP will prompt again.  A new
    # certificate can be generated using the genkey(1) command.
    SSLCertificateFile /etc/pki/CA/certs/httpd.crt  # 配置证书文件所在位置,
    
    #   Server Private Key:
    #   If the key is not combined with the certificate, use this
    #   directive to point at the key file.  Keep in mind that if
    #   you've both a RSA and a DSA private key you can configure
    #   both in parallel (to also allow the use of DSA ciphers, etc.)
    SSLCertificateKeyFile /etc/httpd/ssl/httpd.key # 私钥文件所在位置
    
[root@centos7 httpd]# httpd -t
Syntax OK
[root@centos7 httpd]# systemctl reload httpd
#查看监听端口443
[root@centos7 httpd]# ss -tnl
State       Recv-Q Send-Q                                      Local Address:Port                                                     Peer Address:Port              
LISTEN      0      128                                                     *:22                                                                  *:*                  
LISTEN      0      128                                             127.0.0.1:631                                                                 *:*                  
LISTEN      0      100                                             127.0.0.1:25                                                                  *:*                  
LISTEN      0      128                                             127.0.0.1:6010                                                                *:*                  
LISTEN      0      128                                             127.0.0.1:6011                                                                *:*                  
LISTEN      0      128                                                    :::8080                                                               :::*                  
LISTEN      0      128                                                    :::80                                                                 :::*                  
LISTEN      0      128                                                    :::22                                                                 :::*                  
LISTEN      0      128                                                   ::1:631                                                                :::*                  
LISTEN      0      128                                                    :::8088                                                               :::*                  
LISTEN      0      100                                                   ::1:25                                                                 :::*                  
LISTEN      0      128                                                   ::1:6010                                                               :::*                  
LISTEN      0      128                                                    :::443                                                                :::*                  
LISTEN      0      128                                                   ::1:6011                                                               :::*

6.测试,导入证书文件,并且主机名要和证书中请求的一致

[root@centos7 httpd]# curl https://10.1.252.161/test.html
curl: (60) Peer's Certificate issuer is not recognized. # 没有通过
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
 
[root@centos7 httpd]# curl --cacert /etc/pki/CA/cacert.pem  https://10.1.252.161/test.html
curl: (51) Unable to communicate securely with peer: requested domain name does not match the server's certificate.
 
 # 这里一定要注意要,访问的主机名要和证书中申请的主机名一至,而且要提供证书,才可以正常访问
[root@centos7 httpd]# curl --cacert /etc/pki/CA/cacert.pem  https://www.magedu.com/test.html
<html>
      <head>
           <title>Test Page</title>
      </head>
      <body>
           <h1>My Test Page</h1>
      </body>
</html>

 如上就是配置https的整个过程...

http自带的应用程序

 1.介绍

工具介绍

  • htpasswd:basic认证基于文件实现,用于生成账号和密码的程序;

  • apachectl:httpd自带的服务控制脚本,支持start和stop等子命令;

  • apxs:- APache eXtenSion tool,由httpd-devel包提供,是为httpd增添模块的;

  • rotatelogs:日志滚动工具

           access_log, 

           access_log, access_log.1, ...

  • ab:- Apache HTTP server benchmarking tool 服务器性能压测工具  

  2.ab- web service的压力测试工具 

http压力测试工具:

  • ab,webbench,http_load,jmeter,loadrunner,tcpcopy

ab的原理:

  • ab命令会创建多个并发访问线程,模拟多个访问者同时对某一URL地址进行访问。它的测试目标是基于URL的,因此,它既可以用来测试apache的负载压力,也可以测试nginx、lighthttp、tomcat、IIS等其它Web服务器的压力。

语法:

  • ab [OPTIONS]  [http[s]://]hostname[:port]/path

选项:

  • -n:总的请求数

  • -c:一次请求模拟的并发数

  • -k:以持久连接模拟测试

演示:

主要查看的指标:Requests per second;Time per request:   

# 请求数为5000 ,并发数为100 ,表示同时处理5000个请求并运行100次messages.txt文件
[root@centos7 ~]# ab -n 5000 -c 100 http://10.1.252.161/messages.txt
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 10.1.252.161 (be patient)
Completed 500 requests     # 以10%的请求进度进行完成
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests


Server Software:        Apache/2.4.6  # 版本
Server Hostname:        10.1.252.161  # 地址
Server Port:            80            # 端口
 
Document Path:          /messages.txt #请求的资源
Document Length:        329712 bytes  # 资源长度,即大小

Concurrency Level:      100           # 并行级别
Time taken for tests:   5.188 seconds # 整个测试持续的时间
Complete requests:      5000          # 完成的请求数量
Failed requests:        0
Write errors:           0
Total transferred:      1650115000 bytes  # 总共的传输量
HTML transferred:       1648560000 bytes  # HTML的传输量
Requests per second:    963.81 [#/sec] (mean) # 吞吐率(每秒请求的数量)
Time per request:       103.755 [ms] (mean) # 用户平均请求等待时间(每组100个)
Time per request:       1.038 [ms] (mean, across all concurrent requests) # 上面每组100并发的平均值
Transfer rate:          310623.73 [Kbytes/sec] received # 传送速率
 
Connection Times (ms) # 连接时间(毫秒)三个阶段
              min  mean[+/-sd] median   max
Connect:        0    0   1.0      0      18  # 连接阶段
Processing:     5  103  68.6     77     339  # 处理阶段
Waiting:        1  100  68.2     74     334  # 等待阶段
Total:         12  103  68.5     77     340

Percentage of the requests served within a certain time (ms) # 每批送达请求所用的时间
  50%     77
  66%     87
  75%     98
  80%    114
  90%    239
  95%    303
  98%    320
  99%    323
 100%    340 (longest request)

httpd-2.2与httpd-2.4的不同之处

MPM:

  • prefork:进程模型,两级结构,master/worker, 每worker处理一个请求;

  • worker:线程模型,三级结构,master/worker/thread,每thread处理一个请求;

  • event:事件驱动的线程模型,两级结构,master/worker,每worker响应多个请求;

httpd-2.2的MPM模块为static模块(静态直接编译进去),而非shared模块;

如下:

[root@CentOS6 conf]# httpd -M |grep mpm
 mpm_prefork_module (static)
 
[root@centos7 ~]# httpd -M |grep mpm
 mpm_prefork_module (shared)

wKioL1f8tTCgpCkkAABgFhrmZmc425.png

基于IP的访问控制机制:

httpd-2.4:

  • require ip, require not ip, require host, require not host

httpd-2.2:

  • Order:检查次序

  • Order allow,deny:只有明确Allow的来源地址,才允许访问,其他的均为Deny

  • Order deny,allow

          Allow from:允许访问的来源地址

          Deny from:拒绝访问的来源地址

wKioL1f8w3mxd16-AAAexEC_Pfk183.png

基于主机名的虚拟主机:

  • httpd-2.2: 需在行首添加使用 NameVirtualHost,并注释掉 DoucmentRoot

  • httpd-2.4:无须使用;

各映射的本地文件系统路径内的资源:

  • httpd-2.4:须做显式授权

  • httpd-2.2:无须显式授权

演示: 

http2.2配置基于主机名的虚拟主机

 1.创建虚拟主机的站点目录

[root@CentOS6 conf.d]# mkdir -pv /vhost/www{1,2}
mkdir: created directory `/vhost'
mkdir: created directory `/vhost/www1'
mkdir: created directory `/vhost/www2'

[root@CentOS6 conf.d]# vim /vhost/www1/index.html
www1
[root@CentOS6 conf.d]# vim /vhost/www1/index.html
www2

 2.编辑配置文件/etc/httpd/conf/httpd.conf,注释掉DocumentRoot

wKiom1f8ycjhEm38AAAq4MuzKh8024.png 

3.编辑配置文件添加虚拟主机

 [root@CentOS6 httpd]# vim conf.d/vhosts.conf
  1 NameVirtualHost *:80
  2 
  3 <VirtualHost *:80>
  4       ServerName www1.magedu.com
  5       DocumentRoot /vhost/www1
  6 </VirtualHost>
  7 
  8 <VirtualHost *:80>
  9     ServerName www2.magedu.com
 10     DocumentRoot /vhost/www2
 11 </VirtualHost>
 
[root@CentOS6 httpd]# httpd -t
Syntax OK
[root@CentOS6 httpd]# service httpd reload

 4.测试如下:

[root@CentOS6 httpd]# vim /etc/hosts
  1 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
  2 ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
  3 10.1.0.1  server.magedu.com server
  4 10.1.252.153  www1.magedu.com www2.magedu.com # 添加地址解析
[root@CentOS6 httpd]# curl http://www1.magedu.com
www1
[root@CentOS6 httpd]# curl http://www2.magedu.com
www2