第二十五章 Httpd常见配置

368 阅读15分钟

@[TOC](第二十五章 Httpd常见配置)


Httpd功能特性

  • 虚拟主机
    IP、Port、FQDN
  • CGI:Common Gateway Interface,通用网关接口
  • 反向代理
  • 负载均衡
  • 路径别名
  • 丰富的用户认证机制
    basic
    digest
  • 支持第三方模块

Httpd-2.4

新特性

  • MPM支持运行为DSO机制;以模块形式按需加载
  • event MPM生产环境可用
  • 异步读写机制
  • 支持每模块及每目录的单独日志级别定义
  • 每请求相关的专用配置
  • 增强版的表达式分析式
  • 毫秒级持久连接时长定义
  • 基于FQDN的虚拟主机不需要NameVirutalHost指令
  • 新指令,AllowOverrideList
  • 支持用户自定义变量
  • 更低的内存消耗

Httpd 安装

  • 版本: CentOS 6: 2.2 CentOS 7: 2.4
  • 安装方式: rpm:centos发行版,稳定,建议使用 编译:定制或特殊需求
  • CentOS 7程序环境:httpd-2.4

配置文件: /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/*.conf 检查配置语法: httpd –t

#查看当前httpd软件包信息
[root@centos7 ~]# yum info httpd
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Installed Packages
Name        : httpd
Arch        : x86_64
Version     : 2.4.6		<--对应的版本2.4.6版本
Release     : 88.el7.centos
Size        : 9.4 M
Repo        : installed
From repo   : base
Summary     : Apache HTTP Server
URL         : http://httpd.apache.org/
License     : ASL 2.0
Description : The Apache HTTP Server is a powerful, efficient, and extensible
            : web server.

#安装httpd服务
[root@centos7 ~]# yum install httpd -y

#httpd文件存放相关目录信息
[root@centos7 ~]# ll /etc/httpd/
total 0
drwxr-xr-x 2 root root  37 Jul  1 15:34 conf
drwxr-xr-x 2 root root 119 Jul  1 15:46 conf.d
drwxr-xr-x 2 root root 166 Apr 22 10:31 conf.modules.d
lrwxrwxrwx 1 root root  19 Apr 22 10:31 logs -> ../../var/log/httpd
lrwxrwxrwx 1 root root  29 Apr 22 10:31 modules -> ../../usr/lib64/httpd/modules
lrwxrwxrwx 1 root root  10 Apr 22 10:31 run -> /run/httpd

#检查配置语法、刚刚装上测试一下、出现了一些提示信息
[root@centos7 ~]# httpd -t
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
Syntax OK

Httpd 程序环境

  • 服务单元文件: /usr/lib/systemd/system/httpd.service 配置文件:/etc/sysconfig/httpd
  • 服务控制和启动: systemctl enable|disable httpd.service systemctl {start|stop|restart|status|reload} httpd.service
  • 站点网页文档根目录: /var/www/html
  • 模块文件路径: /etc/httpd/modules /usr/lib64/httpd/modules

Httpd 程序环境

  • 主程序文件: /usr/sbin/httpd
  • 主进程文件: /etc/httpd/run/httpd.pid
  • 日志文件目录: /var/log/httpd access_log: 访问日志 error_log:错误日志
  • 帮助文档包: httpd-manual

Httpd常见配置

1.Httpd服务监听端口

修改监听的IP和Port Listen [IP:]PORT (1) 省略IP表示为本机所有IP (2) Listen指令至少一个,可重复出现多次 Listen 80 Listen 8080
示例: Listen 192.168.1.100:8080 Lsten 80

1.1 默认端口号:80

#启动服务
[root@centos7 ~]# systemctl start httpd
#查看httpd端口号
[root@centos7 ~]# ss -ntlp | grep httpd
LISTEN     0      128         :::80                      :::*                   users:(("httpd",pid=9280,fd=4),("httpd",pid=9279,fd=4),("httpd",pid=9278,fd=4),("httpd",pid=9277,fd=4),("http",pid=9276,fd=4),("httpd",pid=9275,fd=4))

浏览器查看【添加网卡】 在这里插入图片描述

[root@centos7 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1
TYPE="Ethernet"
BOOTPROTO="none"
NAME="eth1"
DEVICE="eth1"
ONBOOT="yes"
IPADDR=172.16.0.7
PREFIX=16
DNS1=114.114.114.114
GATEWAY=172.16.0.2

#重启网卡
[root@centos7 ~]# systemctl restart network

在这里插入图片描述在这里插入图片描述

1.2. 绑定端口号

#httpd配置文件
[root@centos7 ~]# vim /etc/httpd/conf/httpd.conf
...
Listen 192.168.37.7:80		#绑定主机为'192.168.37.7'、端口号'80'、其他主机访问不了
...

#重启httpd访问
[root@centos7 ~]# systemctl restart httpd
#发现httpd端口被绑定、只能'192.168.37.7'访问80端口
[root@centos7 ~]# ss -ntlp | grep httpd
LISTEN     0      128    192.168.37.7:80                       *:*                   users:(("httpd",pid=8021,fd=3),("httpd",pid=8020,fd=3),("httpd",pid=8019,fd=3),("httpd",pid=8016,fd=3),(httpd",pid=8015,fd=3),("httpd",pid=8014,fd=3),("httpd",pid=8013,fd=3),("httpd",pid=8012,fd=3),("httpd",pid=8011,fd=3))

再次浏览器访问 在这里插入图片描述只能192.168.37.7:80访问 在这里插入图片描述

1.3. 绑定多个端口

[root@centos7 ~]# vim /etc/httpd/conf/httpd.conf 
...
Listen 192.168.37.7:80
Listen 8080		<--其他主机只能访问8080端口
...

#重启服务
[root@centos7 ~]# systemctl restart httpd

#发现http服务新增8080端口、谁都可以访问8080端口
[root@centos7 ~]# ss -ntlp | grep httpd
LISTEN     0      128    192.168.37.7:80                       *:*                   users:(("httpd",pid=8180,fd=3),("httpd",pid=8169,fd=3),("httpd",pid=8168,fd=3),("httpd",pid=8167,fd=3),(httpd",pid=8166,fd=3),("httpd",pid=8165,fd=3),("httpd",pid=8164,fd=3))
LISTEN     0      128         :::8080                    :::*                   users:(("httpd",pid=8180,fd=5),("httpd",pid=8169,fd=5),("httpd",pid=8168,fd=5),("httpd",pid=8167,fd=5),("http",pid=8166,fd=5),("httpd",pid=8165,fd=5),("httpd",pid=8164,fd=5))

浏览器访问 在这里插入图片描述在这里插入图片描述

2. 显示服务器版本信息

2.1. 服务器版本信息

[root@centos7 ~]# curl -I 192.168.37.7
HTTP/1.1 403 Forbidden		<--第一次安装、403报错是因为'/var/www/html'目录为空、没有网页信息
Date: Fri, 01 Jul 2022 10:53:55 GMT
Server: Apache/2.4.6 (CentOS)
Last-Modified: Thu, 16 Oct 2014 13:20:58 GMT
ETag: "1321-5058a1e728280"
Accept-Ranges: bytes
Content-Length: 4897
Content-Type: text/html; charset=UTF-8

#添加网页信息
[root@centos7 ~]# cd /var/www/html/
[root@centos7 html]# ls

#测试页面
[root@centos7 html]# vim index.html
<h1>hello world</h1>

#访问192.168.37.7页面
[root@centos7 html]# curl 192.168.37.7
<h1>hello world</h1>		<--页面信息

[root@centos7 html]# curl -I 192.168.37.7
HTTP/1.1 200 OK				<--ok表示正常
Date: Fri, 01 Jul 2022 11:23:52 GMT
Server: Apache/2.4.6 (CentOS)		<--服务器版本Apahche/2.4.6
Last-Modified: Fri, 01 Jul 2022 11:01:38 GMT
ETag: "15-5e2bc4f7425e7"
Accept-Ranges: bytes
Content-Length: 21
Content-Type: text/html; charset=UTF-8

浏览器测试:显示页面信息 在这里插入图片描述

2.2. 把服务器版本信息隐藏【建议使用:ServerTokens Prod】

#把配置文件还原
[root@centos7 html]# vim /etc/httpd/conf/httpd.conf 
...
Listen 80
...

#把文件放在另外一个地方也可以、名字'*.conf'
[root@centos7 html]# vim /etc/httpd/conf.d/test.conf
servertokens prod

#重启服务
[root@centos7 html]# systemctl restart httpd

#查看端口改回80
[root@centos7 html]# ss -ntlp|grep httpd
LISTEN     0      128         :::80                      :::*                   users:(("httpd",pid=9388,fd=4),("httpd",pid=9387,fd=4),("httpd",pid=9386,fd=4),("httpd",pid=9385,fd=4),("http",pid=9384,fd=4),("httpd",pid=9377,fd=4))


[root@centos7 html]# curl -I 192.168.37.7
HTTP/1.1 200 OK
Date: Fri, 01 Jul 2022 11:47:05 GMT
Server: Apache			<--此处只显示服务为Apache、不显示版本
Last-Modified: Fri, 01 Jul 2022 11:01:38 GMT
ETag: "15-5e2bc4f7425e7"
Accept-Ranges: bytes
Content-Length: 21
Content-Type: text/html; charset=UTF-8

3. 持久连接

[root@centos7 html]# cp /etc/fstab test.txt
[root@centos7 html]# ls
index.html  test.txt

浏览器 在这里插入图片描述在这里插入图片描述

#设置持久连接时间
[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
servertokens prod
KeepAliveTimeout 20		<--将持久连接时间改为20s、默认为5s

[root@centos7 html]# systemctl restart httpd

6主机测试

[root@centos6 ~]$ telnet 192.168.37.7 80		#连接192.168.37.7主机80端口
Trying 192.168.37.7...
Connected to 192.168.37.7.
Escape character is '^]'.
GET /index.html HTTP/1.1			<--
host: 1.1.1.1		<--此时ip地址随便写
								<--回车后会出来下面信息
HTTP/1.1 200 OK
Date: Fri, 01 Jul 2022 18:08:35 GMT
Server: Apache
Last-Modified: Fri, 01 Jul 2022 11:01:38 GMT
ETag: "15-5e2bc4f7425e7"
Accept-Ranges: bytes
Content-Length: 21
Content-Type: text/html; charset=UTF-8

<h1>hello world</h1>			<--index.html文件内容
GET /test.txt HTTP/1.1			<--
host: 2.2.2.2	<--此时ip地址随便写
							<--回车后会出来下面信息
HTTP/1.1 200 OK
Date: Fri, 01 Jul 2022 18:08:48 GMT
Server: Apache
Last-Modified: Fri, 01 Jul 2022 17:02:04 GMT
ETag: "279-5e2c1587d3f6b"
Accept-Ranges: bytes
Content-Length: 633
Content-Type: text/plain; charset=UTF-8


#																<--test.txt文件内容
# /etc/fstab
# Created by anaconda on Wed Jan 12 11:00:49 2022
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=eb9228ed-acf9-417b-9f6f-c24b04894d56 /                       xfs     defaults        0 0
UUID=2da9c4ce-5927-40b3-a433-392335d5d9ca /boot                   xfs     defaults        0 0
UUID=c043204c-7375-4c81-a547-8311dff64e29 /data                   xfs     defaults        0 0
UUID=4a072509-3d79-496c-a73e-f8b7b15bf79d swap                    swap    defaults        0 0
dev/sr0	/misc/cd	iso9660	defaults	0 0

4. DNO:Dynamic Shared Object

加载动态模块配置,不需重启即生效

#此目录下专门放模块
[root@centos7 html]# ls /etc/httpd/modules/
#去除所有'#'号开头的行
[root@centos7 html]# grep -v "^ *#" /etc/httpd/conf/httpd.conf
...
Include conf.modules.d/*.conf		#放在'conf.modules.d/'目录下、命名为'*.conf'的都会加载
...

4.1 关闭basic模块

#查看已加载的静态及动态的模块信息|basic模块
[root@centos7 html]# httpd -M|grep basic
 auth_basic_module (shared)				<--
[root@centos7 html]# cd /etc/httpd/conf.modules.d/
[root@centos7 conf.modules.d]# ls
00-base.conf  00-lua.conf  00-proxy.conf    01-cgi.conf
00-dav.conf   00-mpm.conf  00-systemd.conf  10-wsgi.conf
[root@centos7 conf.modules.d]# grep auth *
...
00-base.conf:LoadModule auth_basic_module modules/mod_auth_basic.so
...

#关闭basic模块
[root@centos7 conf.modules.d]# vim 00-base.conf 
...
#LoadModule auth_basic_module modules/mod_auth_basic.so		#注释掉此行、此模块就不加载了
...


[root@centos7 conf.modules.d]# systemctl restart httpd
#发现这个模块不加载了
[root@centos7 conf.modules.d]# httpd -M |grep basic

4.2 开启basic模块

#打开模块
[root@centos7 conf.modules.d]# vim 00-base.conf 
...
LoadModule auth_basic_module modules/mod_auth_basic.so			<--将注释去掉即可
...


[root@centos7 conf.modules.d]# systemctl restart httpd

[root@centos7 conf.modules.d]# httpd -M |grep basic
 auth_basic_module (shared)				<--

#查看静态编译的模块
[root@centos7 conf.modules.d]# httpd -l
Compiled in modules:
  core.c
  mod_so.c
  http_core.c

5. MPM( Multi-Processing Module)多路处理模块

prefork, worker, event 切换使用的MPM

  • 模块配置文件:/etc/httpd/conf.modules.d/00-mpm.conf
  • 启用要启用的MPM相关的LoadModule指令即可
[root@centos7 conf.modules.d]# pwd
/etc/httpd/conf.modules.d

#模块配置文件信息
[root@centos7 conf.modules.d]# vim 00-mpm.conf 
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so		<--prefork模块、默认模块 性能低

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so		<--worker模块(多线程方式) 性能中

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so		<--event模块(多线程方式、比worker多一个监控线程) 性能高

5.1. prefork模型(一个父进程带若干子进程)

[root@centos7 conf.modules.d]# pstree -p |grep httpd
           |-httpd(6595)-+-httpd(7325)
           |             |-httpd(7326)
           |             |-httpd(7328)
           |             |-httpd(7329)
           |             `-httpd(7330)

在这里插入图片描述

#prefork模型推荐配置、添加6行信息内容如下
[root@centos7 conf.modules.d]# vim /etc/httpd/conf.d/test.conf 
servertokens prod
KeepAliveTimeout 20
StartServers 2000		#刚开服务默认开几个
MinSpareServers 2000		#最小的空闲进程
MaxSpareServers 2000		#最大的空闲进程
ServerLimit 2560		#最多进程数,最大值20000
MaxClients  2560		#最大的并发连接数
MaxRequestsPerChild 40000		#子进程最多能处理的请求数量

[root@centos7 conf.modules.d]# systemctl restart httpd

准备测试文件

[root@centos7 conf.modules.d]# cd /var/www/html/
#准备一个大文件
[root@centos7 html]# ll /var/log/messages
-rw------- 1 root root 355044 Jul  4 10:01 /var/log/messages
[root@centos7 html]# cp /var/log/messages m.txt
#查看m.txt权限
[root@centos7 html]# ll 
total 356
-rw-r--r-- 1 root root     21 Jul  1 19:01 index.html
-rw------- 1 root root 355044 Jul  4 10:05 m.txt
-rw-r--r-- 1 root root    633 Jul  2 01:02 test.txt
#更改权限
[root@centos7 html]# chmod 644 m.txt 
#查看m.txt权限是否更改
[root@centos7 html]# ll
total 356
-rw-r--r-- 1 root root     21 Jul  1 19:01 index.html
-rw-r--r-- 1 root root 355044 Jul  4 10:05 m.txt
-rw-r--r-- 1 root root    633 Jul  2 01:02 test.txt

6主机:压力测试

[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/index.html
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
socket: Too many open files (24)

[root@centos6 ~]$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 15667
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024		<--
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 15667
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
[root@centos6 ~]$ ulimit -n 66666
[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/index.html
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        Apache
Server Hostname:        192.168.37.7
Server Port:            80

Document Path:          /index.html
Document Length:        21 bytes

Concurrency Level:      1000
Time taken for tests:   3.079 seconds
Complete requests:      2000
Failed requests:        0
Write errors:           0
Total transferred:      532000 bytes
HTML transferred:       42000 bytes
Requests per second:    649.61 [#/sec] (mean)		<---
Time per request:       1539.381 [ms] (mean)
Time per request:       1.539 [ms] (mean, across all concurrent requests)
Transfer rate:          168.75 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0  224 671.3      0    3021
Processing:     2   29  87.3     19     750
Waiting:        0   29  87.3     19     750
Total:         14  253 688.4     20    3042

Percentage of the requests served within a certain time (ms)
  50%     20
  66%     21
  75%     22
  80%     23
  90%   1028
  95%   1767
  98%   3037
  99%   3040
 100%   3042 (longest request)


[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/m.txt
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        Apache
Server Hostname:        192.168.37.7
Server Port:            80

Document Path:          /m.txt
Document Length:        355044 bytes

Concurrency Level:      1000
Time taken for tests:   9.886 seconds
Complete requests:      2000
Failed requests:        0
Write errors:           0
Total transferred:      745435546 bytes
HTML transferred:       744895644 bytes
Requests per second:    202.30 [#/sec] (mean)		<---
Time per request:       4943.138 [ms] (mean)
Time per request:       4.943 [ms] (mean, across all concurrent requests)
Transfer rate:          73633.83 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        3  488 1067.7     51    7064
Processing:   202 3570 1537.5   3266    9739
Waiting:       13  301 658.9     81    6057
Total:        244 4057 1763.7   3760    9807

Percentage of the requests served within a certain time (ms)
  50%   3760
  66%   4524
  75%   4960
  80%   5228
  90%   6386
  95%   7536
  98%   9322
  99%   9613
 100%   9807 (longest request)

7主机:

[root@centos7 conf.modules.d]# pstree -p |grep httpd|wc -l
2082

5.2. worker模型(多线程方式)

[root@centos7 conf.modules.d]# vim 00-mpm.conf 

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
LoadModule mpm_worker_module modules/mod_mpm_worker.so	<--

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so

#添加worker配置信息、注释掉prefork的配置
[root@centos7 conf.modules.d]# vim /etc/httpd/conf.d/test.conf 
servertokens prod
KeepAliveTimeout 20
ServerLimit 16		<--
StartServers 2		<--
MaxRequestWorkers 150		<--
MinSpareThreads 25		<--
MaxSpareThreads 75		<--
ThreadsPerChild 25		<--
#MinSpareServers 2000		<--
#MaxSpareServers 2000		<--
#ServerLimit 2560		<--
#MaxClients  2560		<--


[root@centos7 conf.modules.d]# systemctl restart httpd
[root@centos7 conf.modules.d]# pstree -p | grep httpd|wc -l
53

6主机

[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/index.html
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        Apache
Server Hostname:        192.168.37.7
Server Port:            80

Document Path:          /index.html
Document Length:        21 bytes

Concurrency Level:      1500
Time taken for tests:   0.721 seconds
Complete requests:      2000
Failed requests:        0
Write errors:           0
Total transferred:      534660 bytes
HTML transferred:       42210 bytes
Requests per second:    2772.43 [#/sec] (mean)		<---
Time per request:       541.042 [ms] (mean)
Time per request:       0.361 [ms] (mean, across all concurrent requests)
Transfer rate:          723.78 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   19  28.9      5      86
Processing:     8   77 161.0     21     628
Waiting:        1   75 161.1     20     627
Total:         21   96 181.6     27     705

Percentage of the requests served within a certain time (ms)
  50%     27
  66%     31
  75%     34
  80%     84
  90%    305
  95%    696
  98%    699
  99%    703
 100%    705 (longest request)
[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/m.txt
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        Apache
Server Hostname:        192.168.37.7
Server Port:            80

Document Path:          /m.txt
Document Length:        355044 bytes

Concurrency Level:      1500
Time taken for tests:   5.328 seconds
Complete requests:      2000
Failed requests:        0
Write errors:           0
Total transferred:      731157585 bytes
HTML transferred:       730635899 bytes
Requests per second:    375.35 [#/sec] (mean)		<---
Time per request:       3996.314 [ms] (mean)
Time per request:       2.664 [ms] (mean, across all concurrent requests)
Transfer rate:          134002.43 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0  547 993.3     22    3016
Processing:     8 1035 1326.3    476    4246
Waiting:        0  835 1232.2    320    3894
Total:        170 1582 1722.0    522    5276

Percentage of the requests served within a certain time (ms)
  50%    522
  66%   1233
  75%   3374
  80%   3674
  90%   4800
  95%   4931
  98%   5201
  99%   5233
 100%   5276 (longest request)

5.3. event模型(多线程方式、比worker多一个监控线程)

[root@centos7 conf.modules.d]# vim 00-mpm.conf 

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
LoadModule mpm_event_module modules/mod_mpm_event.so		<--

[root@centos7 conf.modules.d]# systemctl restart httpd

6主机测试:

[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/index.html
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        Apache
Server Hostname:        192.168.37.7
Server Port:            80

Document Path:          /index.html
Document Length:        21 bytes

Concurrency Level:      1500
Time taken for tests:   0.394 seconds
Complete requests:      2000
Failed requests:        0
Write errors:           0
Total transferred:      536256 bytes
HTML transferred:       42336 bytes
Requests per second:    5079.66 [#/sec] (mean)		<--
Time per request:       295.295 [ms] (mean)
Time per request:       0.197 [ms] (mean, across all concurrent requests)
Transfer rate:          1330.08 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   18  16.4     13      60
Processing:     7   41  59.5     22     292
Waiting:        2   37  59.0     19     287
Total:         19   59  71.3     34     345

Percentage of the requests served within a certain time (ms)
  50%     34
  66%     47
  75%     51
  80%     56
  90%     72
  95%    288
  98%    296
  99%    309
 100%    345 (longest request)
[root@centos6 ~]$ ab -c1500 -n 2000 http://192.168.37.7/m.txt
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.37.7 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        Apache
Server Hostname:        192.168.37.7
Server Port:            80

Document Path:          /m.txt
Document Length:        355044 bytes

Concurrency Level:      1500
Time taken for tests:   9.883 seconds
Complete requests:      2000
Failed requests:        50
   (Connect: 0, Receive: 0, Length: 50, Exceptions: 0)
Write errors:           0
Total transferred:      742507583 bytes
HTML transferred:       741966163 bytes
Requests per second:    202.37 [#/sec] (mean)		<--
Time per request:       7412.332 [ms] (mean)
Time per request:       4.942 [ms] (mean, across all concurrent requests)
Transfer rate:          73368.11 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1  977 2036.5     56    7080
Processing:   660 2662 897.9   2556    9597
Waiting:        1  643 582.5    638    4942
Total:        911 3639 2194.6   2861    9844

Percentage of the requests served within a certain time (ms)
  50%   2861
  66%   3456
  75%   4061
  80%   4839
  90%   6255
  95%   9666
  98%   9837
  99%   9839
 100%   9844 (longest request)

6. 定义'Main' server的文档页面路径(设置网页存放路径)

示例1:自定义网页路径

7主机:

#httpd配置文件
[root@centos7 ~]# vim /etc/httpd/conf/httpd.conf
...
#DocumentRoot "/var/www/html"		#页面存放的目录、注释掉
...
[root@centos7 ~]# vim /etc/httpd/conf.d/test.conf 
DocumentRoot "/data/html"		<--

[root@centos7 ~]# mkdir /data/html
[root@centos7 ~]# echo /data/html/index.html > /data/html/index.html
[root@centos7 ~]# cat /data/html/index.html
/data/html/index.html			<--页面内容

[root@centos7 ~]# systemctl restart httpd

6主机测试;

#报错
[root@centos6 ~]$ curl http://192.168.37.7/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<title>Apache HTTP Server Test Page powered by CentOS</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <!-- Bootstrap -->
    <link href="/noindex/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="noindex/css/open-sans.css" type="text/css" />

<style type="text/css"><!--		 

body {
  font-family: "Open Sans", Helvetica, sans-serif;
  font-weight: 100;
  color: #ccc;
  background: rgba(10, 24, 55, 1);
  font-size: 16px;
}

h2, h3, h4 {
  font-weight: 200;
}

h2 {
  font-size: 28px;
}

.jumbotron {
  margin-bottom: 0;
  color: #333;
  background: rgb(212,212,221); /* Old browsers */
  background: radial-gradient(ellipse at center top, rgba(255,255,255,1) 0%,rgba(174,174,183,1) 100%); /* W3C */
}

.jumbotron h1 {
  font-size: 128px;
  font-weight: 700;
  color: white;
  text-shadow: 0px 2px 0px #abc,
               0px 4px 10px rgba(0,0,0,0.15),
               0px 5px 2px rgba(0,0,0,0.1),
               0px 6px 30px rgba(0,0,0,0.1);
}

.jumbotron p {
  font-size: 28px;
  font-weight: 100;
}

.main {
   background: white;
   color: #234;
   border-top: 1px solid rgba(0,0,0,0.12);
   padding-top: 30px;
   padding-bottom: 40px;
}

.footer {
   border-top: 1px solid rgba(255,255,255,0.2);
   padding-top: 30px;
}

    --></style>
</head>
<body>
  <div class="jumbotron text-center">
    <div class="container">
   	  <h1>Testing 123..</h1>
  		<p class="lead">This page is used to test the proper operation of the <a href="http://apache.org">Apache HTTP server</a> after it has been installed. If you can read this page it means that this site is working properly. This server is powered by <a href="http://centos.org">CentOS</a>.</p>
		</div>
  </div>
  <div class="main">
    <div class="container">
       <div class="row">
  			<div class="col-sm-6">
    			<h2>Just visiting?</h2>
			  		<p class="lead">The website you just visited is either experiencing problems or is undergoing routine maintenance.</p>
  					<p>If you would like to let the administrators of this website know that you've seen this page instead of the page you expected, you should send them e-mail. In general, mail sent to the name "webmaster" and directed to the website's domain should reach the appropriate person.</p>
  					<p>For example, if you experienced problems while visiting www.example.com, you should send e-mail to "webmaster@example.com".</p>
	  			</div>
  				<div class="col-sm-6">
	  				<h2>Are you the Administrator?</h2>
		  			<p>You should add your website content to the directory <tt>/var/www/html/</tt>.</p>
		  			<p>To prevent this page from ever being used, follow the instructions in the file <tt>/etc/httpd/conf.d/welcome.conf</tt>.</p>

	  				<h2>Promoting Apache and CentOS</h2>
			  		<p>You are free to use the images below on Apache and CentOS Linux powered HTTP servers.  Thanks for using Apache and CentOS!</p>
				  	<p><a href="http://httpd.apache.org/"><img src="images/apache_pb.gif" alt="[ Powered by Apache ]"></a> <a href="http://www.centos.org/"><img src="images/poweredby.png" alt="[ Powered by CentOS Linux ]" height="31" width="88"></a></p>
  				</div>
	  		</div>
	    </div>
		</div>
	</div>
	  <div class="footer">
      <div class="container">
        <div class="row">
          <div class="col-sm-6">          
            <h2>Important note:</h2>
            <p class="lead">The CentOS Project has nothing to do with this website or its content,
            it just provides the software that makes the website run.</p>
            
            <p>If you have issues with the content of this site, contact the owner of the domain, not the CentOS project. 
            Unless you intended to visit CentOS.org, the CentOS Project does not have anything to do with this website,
            the content or the lack of it.</p>
            <p>For example, if this website is www.example.com, you would find the owner of the example.com domain at the following WHOIS server:</p>
            <p><a href="http://www.internic.net/whois.html">http://www.internic.net/whois.html</a></p>
          </div>
          <div class="col-sm-6">
            <h2>The CentOS Project</h2>
            <p>The CentOS Linux distribution is a stable, predictable, manageable and reproduceable platform derived from 
               the sources of Red Hat Enterprise Linux (RHEL).<p>
            
            <p>Additionally to being a popular choice for web hosting, CentOS also provides a rich platform for open source communities to build upon. For more information
               please visit the <a href="http://www.centos.org/">CentOS website</a>.</p>
          </div>
        </div>
		  </div>
    </div>
  </div>
</body></html>
#查看部错误原因
[root@centos6 ~]$ curl -I http://192.168.37.7/
HTTP/1.1 403 Forbidden		<--403、因为刚刚没有授权
Date: Mon, 04 Jul 2022 07:02:31 GMT
Server: Apache
Last-Modified: Thu, 16 Oct 2014 13:20:58 GMT
ETag: "1321-5058a1e728280"
Accept-Ranges: bytes
Content-Length: 4897
Content-Type: text/html; charset=UTF-8

7主机:

#添加授权信息
[root@centos7 ~]# vim /etc/httpd/conf.d/test.conf 
DocumentRoot "/data/html"
<Directory "/data/html">		<--对这个 ‘/data/html’目录授权
    Require all granted			<--全部授予
</Directory>					<--

#重启服务
[root@centos7 ~]# systemctl restart httpd

6主机:测试

#查看页面信息、成功
[root@centos6 ~]$ curl http://192.168.37.7/
/data/html/index.html			<--页面内容

示例2:在目录中创建子目录'网站信息 '

7主机:

[root@centos7 ~]# mkdir /data/html/news
[root@centos7 ~]# echo /data/html/news/index.html > /data/html/news/index.html

6主机:查看

[root@centos6 ~]$ curl http://192.168.37.7/news/
/data/html/news/index.html

示例3:软连接形式网页路径

7主机:

[root@centos7 ~]# cd /data/html/
[root@centos7 html]# ls
index.html  news
[root@centos7 html]# mkdir /app/sportsdir/ -pv
[root@centos7 html]# echo /app/sportsdir/index.html > /app/sportsdir/index.html
[root@centos7 html]# ls
index.html  news

#创建软连接
[root@centos7 html]# ln -s /app/sportsdir/index.html sportsdir

#软连接方式
[root@centos7 html]# ll
total 4
-rw-r--r-- 1 root root 22 Jul  4 14:56 index.html
drwxr-xr-x 2 root root 24 Jul  4 15:11 news
lrwxrwxrwx 1 root root 25 Jul  4 15:24 sportsdir -> /app/sportsdir/index.html

6主机测试

[root@centos6 ~]$ curl http://192.168.37.7/sportsdir
/app/sportsdir/index.html

7. 定义站点主页面

[root@centos7 html]# vim /etc/httpd/conf/httpd.conf
...
<IfModule dir_module>
    DirectoryIndex a.txt index.html		<--默认、去目录中找'index.html'文件、添加'a.txt'做为主页面
</IfModule>
...

#重启服务
[root@centos7 html]# systemctl restart httpd

[root@centos7 html]# vim a.txt
a.txt

6主机:测试主站点

#主站点信息、优先找'a.txt'
[root@centos6 ~]$ curl http://192.168.37.7/
a.txt

7主机:如果把'a.txt'主站点删了、就会去找'index.html'

[root@centos7 html]# rm -r a.txt 

6主机:测试

#发现去找'index.html'站点
[root@centos6 ~]$ curl http://192.168.37.7/
/data/html/index.html

错误页面—找不到index.html文件 可以修改 在这里插入图片描述

8. 站点访问控制常见机制

可基于两种机制指明对哪些资源进行何种访问控制 访问控制机制有两种:客户端来源地址,用户账号

  • 文件系统路径:

<Directory “/path"> ... </Directory> <File “/path/file”> ... </File> <FileMatch "PATTERN"> ... </FileMatch>

9. <Directory>中“基于源地址”实现访问控制

  • 9.1 Options:后跟1个或多个以空白字符分隔的选项列表

在选项前的+,- 表示增加或删除指定选项 常见选项: :one:Indexes:指明的URL路径下不存在与定义的主页面资源相符的资源文件时,返回索引列表给用户

[root@centos7 html]# cd /etc/httpd/conf.d/
[root@centos7 conf.d]# ls
autoindex.conf  cobbler.conf  README  test.conf  userdir.conf  welcome.conf
#把403错误页页面改名后、找不到错误页面
[root@centos7 conf.d]# mv welcome.conf welcome.conf.bak
[root@centos7 html]# cd /data/html/
[root@centos7 html]# mv index.html index.txt
[root@centos7 html]# ls
index.txt  news  sportsdir
[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    Options Indexes			<--
</Directory>
...

[root@centos7 html]# systemctl restart httpd

网站的文件夹结构目录出来了(但是软链接文件没有看到) 在这里插入图片描述 :two: FollowSymLinks:允许访问符号链接文件所指向的源文件

[root@centos7 html]# vim /etc/httpd/conf.d/test.conf
...
DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    Options Indexes FollowSymLinks		<--
</Directory>
...

[root@centos7 html]# systemctl restart httpd

在这里插入图片描述 :three: None:全部禁用 :four: All: 全部允许

9.2 AllowOverride

  • 与访问控制相关的哪些指令可以放在指定目录下的.htaccess(由AccessFileName指定)文件中,覆盖之前的配置指令
  • 只对语句有效
  • AllowOverride All: .htaccess中所有指令都有效
  • AllowOverride None: .htaccess 文件无效
  • AllowOverride AuthConfig .htaccess 文件中,除了AuthConfig 其它指 令都无法生效
[root@centos7 html]# vim .htaccess
Options Indexes FollowSymLinks
[root@centos7 html]# pwd
/data/html
[root@centos7 html]# cat .htaccess
Options Indexes FollowSymLinks

[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks		<--注释掉
</Directory>
...


[root@centos7 html]# systemctl restart httpd
#httpd配置文件中、搜索'/\.ht'
[root@centos7 html]# vim /etc/httpd/conf/httpd.conf 
...
<Files ".ht*">
    Require all denied		<--只要访问".ht*"开头的、全部拒绝
</Files>
...

访问不了、因为没有授权 在这里插入图片描述授权

[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All		<--.htaccess中所有指令都有效
</Directory>
...


[root@centos7 html]# systemctl restart httpd

再次刷新、发现可以访问 在这里插入图片描述

  • 9.3. 基于IP的访问控制:

无明确授权的目录,默认拒绝 允许所有主机访问:Require all granted 拒绝所有主机访问:Require all denied 控制特定的IP访问:

Require ip IPADDR:授权指定来源的IP访问 Require not ip IPADDR:拒绝特定的IP访问

控制特定的主机访问:

Require host HOSTNAME:授权特定主机访问 Require not host HOSTNAME:拒绝

HOSTNAME:

FQDN:特定主机 domin.tld:指定域名下的所有主机

7主机:

#比如拒绝所有的conf文件
[root@centos7 html]# vim test.conf
test.conf

6主机:可以访问

[root@centos6 ~]$ curl -I http://192.168.37.7/test.conf
HTTP/1.1 200 OK			<--成功
Date: Tue, 05 Jul 2022 05:02:46 GMT
Server: Apache
Last-Modified: Tue, 05 Jul 2022 05:02:33 GMT
ETag: "a-5e307c2a9ae33"
Accept-Ranges: bytes
Content-Length: 10
Content-Type: text/plain; charset=UTF-8

[root@centos6 ~]$ curl http://192.168.37.7/test.conf
test.conf

7主机:

[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
#方法1
...
<Files "*.conf">
    Require all denied			<--只要是'*.conf'文件、都拒绝访问
</Files>
...
#方法2:正则表达式
<FilesMatch "\.conf$">
    Require all denied
</FilesMatch>


[root@centos7 html]# systemctl restart httpd

6主机:发现不能访问

[root@centos6 ~]$ curl http://192.168.37.7/test.conf
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /test.conf
on this server.</p>
</body></html>
[root@centos6 ~]$ curl -I http://192.168.37.7/test.conf
HTTP/1.1 403 Forbidden
Date: Tue, 05 Jul 2022 05:08:05 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1
  • 示例1:不能有失败,至少有一个成功匹配才成功,即失败优先

7主机:创建'beijing文件夹',希望'37.6'不能访问

#创建'beijing文件夹',希望'37.6'不能访问
[root@centos7 html]# mkdir beijing
[root@centos7 html]# touch beijing/index.html
[root@centos7 html]# echo beijing > beijing/index.html

6主机:可以访问

#现在可以访问
[root@centos6 ~]$ curl http://192.168.37.7/beijing/
beijing

7主机:所有主机都允许、但是拒绝37.6主机

#所有主机都允许、但是拒绝37.6主机
[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
<Directory "/data/html/beijing">
<RequireAll>
Require all granted				<--所有主机都允许
Require not ip 192.168.37.6		<--拒绝37.6主机
</RequireAll>
</Directory>
...


[root@centos7 html]# systemctl restart httpd

6主机:不能访问

[root@centos6 ~]$ curl http://192.168.37.7/beijing/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /beijing/
on this server.</p>
</body></html>

7主机:本机可访问

[root@centos7 html]# curl http://192.168.37.7/beijing/
beijing

也可写成子网掩码形式(如下:拒绝整个'192.168.37.0'网段)

[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
<Directory "/data/html/beijing">
<RequireAll>
Require all granted
Require not ip 192.168.37.0/24
</RequireAll>
</Directory>
...


[root@centos7 html]# systemctl restart httpd

#发现自己也不能访问
[root@centos7 html]# curl http://192.168.37.7/beijing/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /beijing/
on this server.</p>
</body></html>

#用别的网段可以继续访问
[root@centos7 html]# curl http://172.16.0.7/beijing/
beijing
  • 示例2:多个语句有一个成功,则成功,即成功优先<参考示例1> 所有主机都不允许、只有37.6主机可访问 <RequireAny> Require all denied require ip 192.168.37.6 允许特定IP </RequireAny>

10. 日志设定

日志类型:

  • 访问日志
  • 错误日志

错误日志: ErrorLog logs/error_log LogLevel warn LogLevel 可选值: debug, info, notice, warn,error, crit, alert, emerg

#httpd日志存放目录中包括:访问日志'access_log'、错误日志'access_log'
[root@centos7 html]# ls /etc/httpd/logs/
access_log  error_log
#只留下文件中内容
[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
servertokens prod
KeepAliveTimeout 20
StartServers 2000
MaxSpareServers 2000
ServerLimit 2560
MaxClients  2560
MaxRequestsPerChild 40000
DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>
...

#AH00558提示:缺少'ServerName'、此信息不算报错
[root@centos7 html]# httpd -t
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
Syntax OK

[root@centos7 html]# systemctl restart httpd

[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
ServerName test.baidu.com			<--添加ServerName
...

[root@centos7 html]# httpd -t
Syntax OK

日志格式 在这里插入图片描述可参考相关文档信息 在这里插入图片描述跳转日志

#test1.html页面内容
[root@centos7 html]# vim test1.html 
<html>
<head>
<title></title>
</head>
<body>
<p><a href=http://192.168.37.7/test2.html>link</a>你好</p>	#点击页面信息、跳转至test2.html页面
</body>
</html>

#test2.html页面内容
[root@centos7 html]# vim test2.html 
test2.html
#监控访问日志
[root@centos7 html]# tail -f /var/log/httpd/access_log
...
192.168.37.1 - - [05/Jul/2022:16:23:01 +0800] "GET /test2.html HTTP/1.1" 200 10 "http://192.168.37.7/test1.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0"
192.168.37.1 - - [05/Jul/2022:16:25:56 +0800] "GET /test2.html HTTP/1.1" 200 11 "http://192.168.37.7/test1.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0"

浏览器访问'test1.html' 在这里插入图片描述 在这里插入图片描述在这里插入图片描述 在这里插入图片描述在这里插入图片描述

#访问量倒序排列
[root@centos7 html]# awk '{print $1}' /var/log/httpd/access_log |sort |uniq -c|sort -nr
  94800 192.168.37.6
   1231 ::1
    358 192.168.37.1
      4 192.168.37.7
      2 192.168.37.18
      1 172.16.0.7

11. 设定默认字符集

AddDefaultCharset UTF-8 此为默认值 中文字符集:GBK, GB2312, GB18030

#查看字符集
[root@centos7 html]# iconv -l

12. 定义路径别名

通过别名方式、访问到另一个路径(访问bbs的时候、文件来自/app/forum目录) 7主机:

[root@centos7 html]# mkdir /app/forum
[root@centos7 html]# echo /app/forum/index.html > /app/forum/index.html
[root@centos7 html]# vim /etc/httpd/conf.d/test.conf 
...
alias /bbs/ /app/forum/			<--把'/bbs/'映射成'/app/forum/'目录
<Directory "/app/forum">		<--针对此目录
    Require all granted			<--授权
</Directory>					<--
...


[root@centos7 html]# systemctl restart httpd

6主机:测试(如果不能查看、在7主机用'iptables -F'关闭防火墙策略、再测试)

[root@centos6 ~]$ curl http://192.168.37.7/bbs/
/app/forum/index.html

在这里插入图片描述

13. 基于用户的访问控制

:one:认证质询:WWW-Authenticate:响应码为401,拒绝客户端请求,并说明要求客户端提供账号和密码 :two:认证:Authorization:客户端用户填入账号和密码后再次发送请求报文;认证通过时,则服务器发送响应的资源 :three:认证方式两种:

  • basic:明文
  • digest:消息摘要认证,兼容性差

:four:安全域:需要用户认证后方能访问的路径;应该通过名称对其进行标识,以便于告知用户认证的原因
:five:用户的账号和密码

  • 虚拟账号:仅用于访问某服务时用到的认证标识
  • 存储:文本文件,SQL数据库,ldap目录存储,nis等

13.1. basic认证配置示例:

(1) 提供账号和密码存储(文本文件) 使用专用命令完成此类文件的创建及用户管理 htpasswd [options] /PATH/HTTPD_PASSWD_FILE username -c 自动创建文件,仅应该在文件不存在时使用 -p 明文密码 -d CRYPT格式加密,默认 -m md5格式加密 -s sha格式加密 -D 删除指定用户

实验:实现basic用户验证

前提

7主机:

[root@centos7 html]# pwd
/data/html
[root@centos7 html]# mkdir admin
[root@centos7 html]# echo /data/html/admin/index.html > admin/index.html
[root@centos7 html]# cat admin/index.html 
/data/html/admin/index.html

#主站点页面
[root@centos7 html]# vim index.html
<h1>www.baidu.com</h1>

6主机:不需要验证就可访问

[root@centos6 ~]$ curl http://192.168.37.7/
<h1>www.baidu.com</h1>
[root@centos6 ~]$ curl http://192.168.37.7/admin/
/data/html/admin/index.html

7主机:

[root@centos7 html]# cd /etc/httpd/conf.d/
[root@centos7 conf.d]# rpm -qf `which htpasswd`
httpd-tools-2.4.6-88.el7.centos.x86_64		#如果没有htpasswd工具、需要安装'httpd-tools'

注意:第一次创建需要‘-c’、第二次在写入不要加’-c、否则第二次会把第一次的覆盖、如下‘

#-c自动创建文件,仅在文件不存在时使用、注意:第一次创建需要‘-c’
[root@centos7 conf.d]# htpasswd -c .httpuser bob
New password: 				#输入密码123.com
Re-type new password:  		#再次输入密码123.com
Adding password for user bob
[root@centos7 conf.d]# cat .httpuser 		#用户账号存放文件
bob:$apr1$M2G.lsI0$byR4mo4YWc.UF5gJAJPdN0		#第一次创建

#第二次创建
[root@centos7 conf.d]# htpasswd -c .httpuser alice
New password:   				#输入密码123.com
Re-type new password:   		#再次输入密码123.com
Adding password for user alice
[root@centos7 conf.d]# cat .httpuser 
alice:$apr1$hxTJguO1$r3Tdg74Tj0ovtrzy1fu3p.			#注意:因为加'-c'选项。第二次创建、把第一次的覆盖了、文件中只有alice

#所有再次添加不需要'-c'选项、在现有的文件中增加信息
[root@centos7 conf.d]# htpasswd .httpuser bob
New password:    				#再次输入密码123.com
Re-type new password:    		#再次输入密码123.com
Adding password for user bob
[root@centos7 conf.d]# cat .httpuser 
alice:$apr1$hxTJguO1$r3Tdg74Tj0ovtrzy1fu3p.			<--
bob:$apr1$dScNmVel$nYayM4zo/LLEb2DCirzGn1			<--

(2) 定义安全域 <Directory “/path"> Options None AllowOverride None AuthType Basic AuthName "String“ AuthUserFile "/PATH/HTTPD_USER_PASSWD_FILE" Require user username1 username2 ... </Directory> 允许账号文件中的所有用户登录访问: Require valid-user

方法1
#定义安全域、指定alice可以访问
[root@centos7 conf.d]# cat test.conf 
servertokens prod
KeepAliveTimeout 20
StartServers 2000
MaxSpareServers 2000
ServerLimit 2560
MaxClients  2560
MaxRequestsPerChild 40000
DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

<Directory "/data/html/admin">		<--针对"/data/html/admin"启用验证功能
    AuthType Basic					<--启用basic验证
    AuthName "Admin Page"			<--弹出对话框描述语句
    AuthUserFile "/etc/httpd/conf.d/.httpuser"		<--账号文件路径
    Require user alice				<--允许alice访问
</Directory>

#检查httpd语法
[root@centos7 conf.d]# httpd -t
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
Syntax OK


[root@centos7 conf.d]# systemctl restart httpd

浏览器测试:alice可登陆、bob不能登陆 在这里插入图片描述 输入指定用户密码即可登陆 在这里插入图片描述成功 在这里插入图片描述

#定义安全域、允许账号文件中所有人访问
[root@centos7 conf.d]# vim test.conf
...
<Directory "/data/html/admin">
    AuthType Basic
    AuthName "Admin Page"
    AuthUserFile "/etc/httpd/conf.d/.httpuser"			<--账号文件路径
    Require valid-user		<--允许'.httpuser'文件中的所有用户登录访问
</Directory>
...


[root@centos7 conf.d]# systemctl restart httpd

浏览器测试:bob能否登陆 在这里插入图片描述

方法2

也可将验证信息文件、直接放到 ‘admin’目录下

[root@centos7 conf.d]# vim test.conf 
...
<Directory "/data/html/admin">
    #AuthType Basic					<--
    #AuthName "Admin Page"			<--
    #AuthUserFile "/etc/httpd/conf.d/.httpuser"				<--
    #Require valid-user				<--
    allowoverride authconfig				<--在/data/html/admin文件夹里、我的配置是由‘.htaccess’
</Directory>
...

[root@centos7 conf.d]# cd /data/html/admin
[root@centos7 admin]# ls
index.html

#验证信息
[root@centos7 admin]# vim .htaccess
AuthType Basic
AuthName "Admin Page"
AuthUserFile "/etc/httpd/conf.d/.httpuser"
Require valid-user


[root@centos7 admin]# systemctl restart httpd

浏览器测试:bob和alice都可登陆 在这里插入图片描述在这里插入图片描述 删除用户指令、或vi进到文件中删除

#账号信息存储文件
[root@centos7 admin]# cat /etc/httpd/conf.d/.httpuser 
alice:$apr1$hxTJguO1$r3Tdg74Tj0ovtrzy1fu3p.
bob:$apr1$dScNmVel$nYayM4zo/LLEb2DCirzGn1

#删除bob用户
[root@centos7 admin]# htpasswd -D /etc/httpd/conf.d/.httpuser bob
Deleting password for user bob

#bob用户没了
[root@centos7 admin]# cat /etc/httpd/conf.d/.httpuser 
alice:$apr1$hxTJguO1$r3Tdg74Tj0ovtrzy1fu3p.

实验:基于组账号进行认证

特定组可以访问 'g1组:不能访问'、'g2组:可以访问'。

[root@centos7 admin]# cd -
/etc/httpd/conf.d
#创建组文件
[root@centos7 conf.d]# vim .httpgroup
g1: bob alice			<--组1:bob、alice
g2: jack rose			<--组2:jack、rose
#添加用户到用户文件。密码设置为123.com
[root@centos7 conf.d]# htpasswd .httpuser bob
[root@centos7 conf.d]# htpasswd .httpuser jack
[root@centos7 conf.d]# htpasswd .httpuser rose

#查看用户账号文件、用户添加情况
[root@centos7 conf.d]# cat .httpuser 
alice:$apr1$hxTJguO1$r3Tdg74Tj0ovtrzy1fu3p.
bob:$apr1$cfa8IDC0$UyofwVRZs7wf6M.lTHYkx.			<--
jack:$apr1$IbtXRdQh$Xk0Y4Idj8D89FWt0mCOq91			<--
rose:$apr1$fGymHWF/$zn8LVzmlTMqH0VEDqNRp80			<--
[root@centos7 conf.d]# cd /data/html/admin
[root@centos7 admin]# vim .htaccess 
...
AuthType Basic
AuthName "Admin Page"
AuthUserFile "/etc/httpd/conf.d/.httpuser"
#Require valid-user				<--注释掉此行、否则'.httpuser'文件中所有账号都能访问
AuthGroupFile "/etc/httpd/conf.d/.httpgroup"			<--组文件路径
Require group g2			<--允许'.httpgroup'中哪些组访问、如:'g2'
...


[root@centos7 admin]# systemctl restart httpd

浏览器测试‘http://192.168.37.7/admin/’结果:'g1组:不能访问'、'g2组:可以访问'。

远程客户端和用户验证的控制 Satisfy ALL|Any

  • ALL 客户机IP和用户验证都需要通过才可以
  • Any客户机IP和用户验证,有一个满足即可

示例: Require valid-user <RequireAll>
Require all granted Require not ip 172.16.1.1
</RequireAll> Satisfy Any

14. 实现用户家目录的http共享

基于模块mod_userdir.so实现

[root@centos7 admin]# httpd -M |grep user
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
 authz_user_module (shared)
 userdir_module (shared)

14.1. 把王的家目录共享(都可访问)

#'wang'用户家目录所在位置
[root@centos7 admin]# cd /home/wang/
[root@centos7 wang]# ls


[root@centos7 wang]# vim /etc/httpd/conf.d/userdir.conf 
#
# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received.
#
# The path to the end user account 'public_html' directory must be
# accessible to the webserver userid.  This usually means that ~userid
# must have permissions of 711, ~userid/public_html must have permissions
# of 755, and documents contained therein must be world-readable.
# Otherwise, the client will only receive a "403 Forbidden" message.
#
<IfModule mod_userdir.c>			<--在'mod_userdir'模块中
    #
    # UserDir is disabled by default since it can confirm the presence
    # of a username on the system (depending on home directory
    # permissions).
    #
    #UserDir disabled				<--默认不允许共享家目录、注释掉

    #
    # To enable requests to /~user/ to serve the user's public_html
    # directory, remove the "UserDir disabled" line above, and uncomment
    # the following line instead:
    # 
    UserDir public_html				<--启用后、会把这个家目录共享
</IfModule>

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory "/home/*/public_html">			<--注释掉
#    AllowOverride FileInfo AuthConfig Limit Indexes					<--注释掉
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec		<--注释掉
#    Require method GET POST OPTIONS		<--注释掉
#</Directory>								<--注释掉

<Directory "/home/wang/public_html">		<--针对此目录
    Require all granted						<--授权
</Directory>								<--

#重启服务
[root@centos7 wang]# systemctl restart httpd
[root@centos7 wang]# mkdir public_html
[root@centos7 wang]# echo wanghome > public_html/index.html
[root@centos7 wang]# cat public_html/index.html
wanghome

浏览器 在这里插入图片描述

#查看访问日志
[root@centos7 conf.d]# tail -f /var/log/httpd/access_log 

发现访问王的信息、403被拒绝 在这里插入图片描述

#查看错误日志
[root@centos7 conf.d]# tail -f /var/log/httpd/error_log

在这里插入图片描述

#查看家目录'wang'权限
[root@centos7 conf.d]# ll /home/
total 0
drwx------. 4 wang wang 97 Jul  6 13:19 wang			<--没有访问权限

#用ACL设置权限apache权限、'谁:apache:执行权限'给/home/wang
[root@centos7 conf.d]# setfacl -m u:apache:x /home/wang
[root@centos7 conf.d]# getfacl /home/wang/
getfacl: Removing leading '/' from absolute path names
# file: home/wang/
# owner: wang
# group: wang
user::rwx
user:apache:--x
group::---
mask::--x
other::---

浏览器测试 在这里插入图片描述

14.2. 把王的家目录共享(需要验证):

[root@centos7 httpd]# vim /etc/httpd/conf.d/userdir.conf 
...
#<Directory "/home/wang/public_html">		<--删除或注释掉此3行、否则和下面冲突
#    Require all granted		<--
#</Directory>					<--

<Directory "/home/wang/public_html">
    AuthType Basic				<--启用basic验证
    AuthName "wanghome Page"	<--弹出对话框描述语句
    AuthUserFile "/etc/httpd/conf.d/.httpuser"		<--账号文件路径
    Require valid-user			<--允许'.httpuser'文件中的所有用户登录访问
</Directory>
...


[root@centos7 conf.d]# systemctl restart httpd
#账号文件中有4个用户
[root@centos7 conf.d]# cat .httpuser 
alice:$apr1$hxTJguO1$r3Tdg74Tj0ovtrzy1fu3p.
bob:$apr1$cfa8IDC0$UyofwVRZs7wf6M.lTHYkx.
jack:$apr1$IbtXRdQh$Xk0Y4Idj8D89FWt0mCOq91
rose:$apr1$fGymHWF/$zn8LVzmlTMqH0VEDqNRp80

浏览器测试结果:4个用户都可访问 在这里插入图片描述

15. ServerSignature On | Off | EMail

当客户请求的网页并不存在时,服务器将产生错误文档,如果打开了 ServerSignature选项,错误文档的最后一行将包含服务器的名字、Apache的版本等信息,如果不对外显示这些信息,就可以将这个参数设置为Off 设置为Email,将显示ServerAdmin 的Email提示

在这里插入图片描述

16. status页面(可实现状态查看)

[root@centos7 httpd]# httpd -M |grep status
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
 status_module (shared)
[root@centos7 httpd]# pwd
/etc/httpd
[root@centos7 httpd]# cd conf.d/

#配置信息
[root@centos7 conf.d]# vim test.conf
...
<Location "/status">
    SetHandler server-status
</Location>
...

[root@centos7 conf.d]# httpd -t
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
Syntax OK
[root@centos7 conf.d]# systemctl restart httpd

浏览器测试:查看状态信息(所有网段都能访问) 在这里插入图片描述在这里插入图片描述

指定网段访问

[root@centos7 conf.d]# vim test.conf 
...
<Location "/status">
    SetHandler server-status
<requireany>			<--
require all denied			 		<--拒绝所有
require ip 192.168.37.0/24			<--指定网段访问
</requireany>			<--
</Location>			<--
...


[root@centos7 conf.d]# systemctl restart httpd

浏览器测试:结果 在这里插入图片描述在这里插入图片描述

17. 虚拟主机

站点标识: socket

  • IP相同,但端口不同
  • IP不同,但端口均为默认端口
  • FQDN不同:请求报文中首部 Host: www.magedu.com .

有三种实现方案:

  • 基于ip:为每个虚拟主机准备至少一个ip地址
  • 基于port:为每个虚拟主机使用至少一个独立的port
  • 基于FQDN:为每个虚拟主机使用至少一个FQDN

17. 1. 基于ip(多虚拟主机)

7主机

[root@centos7 conf.d]# cd /data/
#创建三个站点目录
[root@centos7 data]# mkdir {a,b,c}site

#创建三个网站页面文件
[root@centos7 data]# echo www.a.com > asite/index.html
[root@centos7 data]# echo www.b.com > bsite/index.html
[root@centos7 data]# echo www.c.com > csite/index.html
#临时添加三个地址
[root@centos7 data]# ip a a 192.168.37.101/24 dev eth0
[root@centos7 data]# ip a a 192.168.37.102/24 dev eth0
[root@centos7 data]# ip a a 192.168.37.103/24 dev eth0
[root@centos7 data]# vim /etc/httpd/conf.d/test.conf 
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

<virtualhost "192.168.37.101:80">			<--a站点相关信息
documentroot /data/asite			<--主页面位置
CustomLog "logs/asite_access_log" combined		<--a站点日志文件存放路径
<Directory "/data/asite">					<--针对此文件
    Require all granted			<--权限全部授权
</Directory>
</virtualhost>

<virtualhost "192.168.37.102:80">			<--b站点相关信息
documentroot /data/bsite
CustomLog "logs/bsite_access_log" combined
<Directory "/data/bsite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "192.168.37.103:80">			<--c站点相关信息
documentroot /data/csite
CustomLog "logs/csite_access_log" combined
<Directory "/data/csite">
    Require all granted
</Directory>
</virtualhost>

#重新加载
[root@centos7 data]# systemctl reload httpd

6主机:测试

#添加dns
[root@centos6 ~]$ vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.37.101 www.a.com		<--添加dns
192.168.37.102 www.b.com		<--
192.168.37.103 www.c.com		<--

[root@centos6 ~]$ curl www.a.com
www.a.com
[root@centos6 ~]$ curl www.b.com
www.b.com
[root@centos6 ~]$ curl www.c.com
www.c.com

[root@centos6 ~]$ curl 192.168.37.101
www.a.com
[root@centos6 ~]$ curl 192.168.37.102
www.b.com
[root@centos6 ~]$ curl 192.168.37.103
www.c.com

17. 2. 基于port(多虚拟主机)

7主机

[root@centos7 data]# vim /etc/httpd/conf.d/test.conf 

<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

listen 81		<--监听端口
listen 82		<--监听端口
listen 83		<--监听端口

<virtualhost "*:81">			<--基于端口号81
documentroot /data/asite
CustomLog "logs/asite_access_log" combined
<Directory "/data/asite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:82">			<--基于端口号82
documentroot /data/bsite
CustomLog "logs/bsite_access_log" combined
<Directory "/data/bsite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:83">			<--基于端口号83
documentroot /data/csite
CustomLog "logs/csite_access_log" combined
<Directory "/data/csite">
    Require all granted
</Directory>
</virtualhost>


[root@centos7 data]# systemctl restart httpd

6主机

[root@centos6 ~]$ vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.37.7 www.a.com www.b.com www.c.com		<--

[root@centos6 ~]$ curl www.a.com:81
www.a.com
[root@centos6 ~]$ curl www.a.com:82
www.b.com
[root@centos6 ~]$ curl www.a.com:83
www.c.com

17.3. 基于FQDN(主机头的多虚拟主机)

7主机:

[root@centos7 data]# pwd
/data


[root@centos7 data]# vim /etc/httpd/conf.d/test.conf 
DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

<virtualhost "*:80">			<--
documentroot /data/asite
servername www.a.com			<--主机头
CustomLog "logs/asite_access_log" combined
<Directory "/data/asite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:80">			<--
documentroot /data/bsite
servername www.b.com			<--
CustomLog "logs/bsite_access_log" combined
<Directory "/data/bsite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:80">			<--
documentroot /data/csite
servername www.c.com			<--
CustomLog "logs/csite_access_log" combined
<Directory "/data/csite">
    Require all granted
</Directory>
</virtualhost>

#重启服务
[root@centos7 data]# systemctl restart httpd

6主机:

[root@centos6 ~]$ vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.37.7 www.a.com www.b.com www.c.com		<--


[root@centos6 ~]$ curl www.a.com
www.a.com
[root@centos6 ~]$ curl www.b.com
www.b.com
[root@centos6 ~]$ curl www.c.com
www.c.com

mod_deflate模块(压缩)

[root@centos7 data]# httpd -M |grep deflate
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
 deflate_module (shared)
#httpd模块文件存放路径
[root@centos7 data]# cd /etc/httpd/conf.modules.d/
[root@centos7 conf.modules.d]# cat 00-base.conf |grep deflate
LoadModule deflate_module modules/mod_deflate.so
[root@centos7 conf.modules.d]# cd /data/
[root@centos7 data]# ls 
asite  bsite  csite  html
[root@centos7 data]# ll /var/log/messages -h
-rw------- 1 root root 3.7M Jul  7 10:01 /var/log/messages
[root@centos7 data]# chmod a+r /data/asite/m.txt
[root@centos7 data]# ll /data/asite/m.txt
-rw-r--r-- 1 root root 3860684 Jul  7 10:02 /data/asite/m.txt

6主机:

#此时可以看到内容
[root@centos6 ~]$ curl 192.168.37.7/m.txt

在这里插入图片描述 7主机:

[root@centos7 data]# vim /etc/httpd/conf.d/test.conf 

DocumentRoot "/data/html"
<Directory "/data/html">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

<virtualhost "*:80">
documentroot /data/asite
servername www.a.com
CustomLog "logs/asite_access_log" combined
<Directory "/data/asite">
    Require all granted
</Directory>
AddOutputFilterByType DEFLATE text/plain		<--针对文本压缩
AddOutputFilterByType DEFLATE text/html			<--针对html压缩
DeflateCompressionLevel 9			<--启用最高压缩比9
</virtualhost>

<virtualhost "*:80">
documentroot /data/bsite
servername www.b.com
CustomLog "logs/bsite_access_log" combined
<Directory "/data/bsite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:80">
documentroot /data/csite
servername www.c.com
CustomLog "logs/csite_access_log" combined
<Directory "/data/csite">
    Require all granted
</Directory>
</virtualhost>


[root@centos7 data]# systemctl restart httpd

浏览器(火狐)测试: 在这里插入图片描述 6主机:

[root@centos6 ~]$ curl -I --compressed 192.168.37.7/m.txt
HTTP/1.1 200 OK
Date: Thu, 07 Jul 2022 02:30:07 GMT
Server: Apache/2.4.6 (CentOS) mod_wsgi/3.4 Python/2.7.5
Last-Modified: Thu, 07 Jul 2022 02:02:38 GMT
ETag: "3ae8cc-5e32d7adfe1e2-gzip"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Encoding: gzip		 <--
Content-Type: text/plain; charset=UTF-8

https

实验一:https安全网络(自签名证书)

[root@centos7 data]# httpd -M |grep ssl
#安装mod_ssl模块
[root@centos7 data]# yum install mod_ssl -y

[root@centos7 data]# 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 data]# httpd -M |grep ssl
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using centos7.localdomain. Set the 'ServerName' directive globally to suppress this message
 ssl_module (shared)
#查看配置文件
[root@centos7 data]# vim /etc/httpd/conf.d/ssl.conf
...
SSLCertificateFile /etc/pki/tls/certs/localhost.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/pki/tls/private/localhost.key			<--私钥文件路径
...
#查看端口信息、有80、没有443
[root@centos7 data]# ss -ntl
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
...
LISTEN      0      128            :::80                         :::*                  
...

#重启服务
[root@centos7 data]# systemctl restart httpd

#再次查看端口信息、发现443端口
[root@centos7 data]# ss -ntl
State       Recv-Q Send-Q  Local Address:Port                 Peer Address:Port  
...            
LISTEN      0      128                :::80                             :::*                  
LISTEN      0      128                :::443                            :::*                  
...

6主机

#访问不加密网站、可以访问
[root@centos6 ~]$ curl http://www.a.com/
www.a.com
[root@centos6 ~]$ curl http://www.b.com/
www.b.com

#访问加密网站、提示需要验证证书
[root@centos6 ~]$ curl https://www.b.com/
curl: (60) Peer certificate cannot be authenticated with known CA certificates
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.

#-k忽略证书检查 
[root@centos6 ~]$ curl -k https://www.b.com/
<h1>www.baidu.com</h1>		<--发现访问的是默认主站点目录、不是www.b.com

7主机

#查看httpd配置文件信息
[root@centos7 data]# vim /etc/httpd/conf/httpd.conf 
...
#DocumentRoot "/var/www/html"		 <--发现主站点目录文件、被注释掉了
...
#文件路径写到了、我们自定义'test.conf'中
[root@centos7 data]# vim /etc/httpd/conf.d/test.conf 
...
DocumentRoot "/data/html"		<--自定义主站点目录文件
...

[root@centos7 data]# pwd
/data
#默认主站点所在目录文件
[root@centos7 data]# cat html/index.html 
<h1>www.baidu.com</h1>		<--内容
[root@centos7 data]# cp asite/m.txt html

#证书文件
[root@centos7 data]# cat /etc/pki/tls/certs/localhost.crt 

#查看证书文件信息
[root@centos7 data]# openssl x509 -in /etc/pki/tls/certs/localhost.crt -noout -text

#导出文件安装即可
[root@centos7 data]# sz /etc/pki/tls/certs/localhost.crt

浏览器(IE)测试:成功 在这里插入图片描述

实验二:利用私有CA、实现HTTPS

三台主机 caserver:18 httpd:7 client:6

  • 1 建立CA ca主机
[root@caserver ~]# cd /etc/pki/CA/
[root@caserver CA]# ls
certs  crl  newcerts  private
[root@caserver CA]# tree
.
├── certs
├── crl
├── newcerts
└── private

4 directories, 0 files
#生成CA私钥
[root@caserver CA]# (umask 077;openssl genrsa -out private/cakey.pem 4096)
Generating RSA private key, 4096 bit long modulus
.................................++
..................................................................++
e is 65537 (0x10001)
#对CA私钥签名
[root@caserver CA]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3650 <<EOF
> CN
> beijing
> beijing
> magedu
> devops
> ca.magedu.com
> admin@magedu.com
> EOF
#查看证书信息
[root@caserver CA]# openssl x509 -in cacert.pem -noout  -text

#创建文件
[root@caserver CA]# touch /etc/pki/CA/index.txt
#创建第一个从'01'开始
[root@caserver CA]# echo 01 > /etc/pki/CA/serial
  • 2 申请证书 httpd主机:
[root@httpd ~]# cd /etc/httpd/conf.d/
#创建目录、存放ca证书
[root@httpd conf.d]# mkdir ssl

[root@httpd conf.d]# cd ssl

#⽣成私钥
[root@httpd ssl]# (umask 066;openssl genrsa -out httpd.key 1024)
Generating RSA private key, 1024 bit long modulus
..++++++
.++++++
e is 65537 (0x10001)
#⽣成证书申请⽂件
[root@httpd ssl]# openssl req -new -key httpd.key -out httpd.csr
CN			<--国家:一样
beijing		<--省:一样
beijing		<--市:可不一样
magedu		<--公司:一样
devios		<--组织:可不一样
www.a.com	<--网站:可不一样、需要针对以后要是用的网站名
邮件地址为空,直接回车;
根据要求,输入相应信息即可。

将httpd主机的ca请求⽂件发送到caservier主机上:

[root@httpd ssl]# scp httpd.csr 192.168.37.18:/etc/pki/CA
  • 3 颁发证书 ca主机:
[root@caserver CA]# ls
cacert.pem  certs  crl  httpd.csr  index.txt  newcerts  private  serial
#颁发证书、有效期100天
[root@caserver CA]# openssl ca -in /etc/pki/CA/httpd.csr -out /etc/pki/CA/certs/httpd.crt -days 100
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: Jul  8 08:50:39 2022 GMT
            Not After : Oct 16 08:50:39 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = beijing
            organizationName          = magedu
            organizationalUnitName    = devops
            commonName                = www.a.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                5B:DB:07:2F:DD:82:D7:7F:20:93:48:74:6A:7B:21:4B:D3:A4:59:9B
            X509v3 Authority Key Identifier: 
                keyid:45:ED:CA:84:1B:45:26:7A:CD:5B:75:E2:F2:77:47:56:62:27:FD:71

Certificate is to be certified until Oct 16 08:50:39 2022 GMT (100 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@caserver CA]# ls
cacert.pem  crl        index.txt       index.txt.old  private  serial.old
certs       httpd.csr  index.txt.attr  newcerts       serial

[root@caserver CA]# tree
.
├── cacert.pem
├── certs
│   └── httpd.crt		#证书所在位置
├── crl
├── httpd.csr
├── index.txt
├── index.txt.attr
├── index.txt.old
├── newcerts
│   └── 01.pem
├── private
│   └── cakey.pem
├── serial
└── serial.old

4 directories, 10 files
[root@caserver CA]# scp /etc/pki/CA/certs/httpd.crt 192.168.37.7:/etc/httpd/conf.d/ssl/
#ca自己证书也要复制过去
[root@caserver CA]# scp /etc/pki/CA/cacert.pem 192.168.37.7:/etc/httpd/conf.d/ssl/
  • 4 修改配置文件 httpd主机:
#可看到证书文件
[root@httpd ssl]# ll
total 20
-rw-r--r-- 1 root root 2114 Jul  8 17:28 cacert.pem
-rw-r--r-- 1 root root 5040 Jul  8 17:24 httpd.crt		<--自签名证书文件
-rw-r--r-- 1 root root  651 Jul  8 16:37 httpd.csr
-rw------- 1 root root  887 Jul  8 16:32 httpd.key		<--私钥
#把原来两行注释掉替换成我们自己的
[root@httpd ssl]# vim /etc/httpd/conf.d/ssl.conf 
...
#SSLCertificateFile /etc/pki/tls/certs/localhost.crt		<--注释掉
SSLCertificateFile /etc/httpd/conf.d/ssl/httpd.crt			<--自己证书路径

#SSLCertificateKeyFile /etc/pki/tls/private/localhost.key	<--注释掉
SSLCertificateKeyFile /etc/httpd/conf.d/ssl/httpd.key		<--自己私钥证书路径

#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt		<--注释掉
SSLCACertificateFile /etc/httpd/conf.d/ssl/cacert.pem		<--CA证书路径
...

[root@httpd ssl]# systemctl restart httpd
导出证书
[root@httpd ssl]# sz cacert.pem 
  • Windows主机测试

在这里插入图片描述更改hosts 在这里插入图片描述双击'证书'安装--当前用户 在这里插入图片描述 浏览器(ie)查看 在这里插入图片描述6主机:验证

[root@centos6 ~]$ rz -E
rz waiting to receive.

[root@centos6 ~]$ curl https://www.a.com/
curl: (60) Peer certificate cannot be authenticated with known CA certificates
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@centos6 ~]$ curl -k https://www.a.com/
<h1>www.baidu.com</h1>

#curl加上CA路径、跟上文件名、加密网站、也可以访问
[root@centos6 ~]$ curl --cacert cacert.pem.crt https://www.a.com/
<h1>www.baidu.com</h1>

#测试基于https访问相应的主机
[root@centos6 ~]$ openssl s_client -connect www.a.com:443
CONNECTED(00000003)
depth=1 C = CN, ST = beijing, L = beijing, O = magedu, OU = devops, CN = ca.magedu.com, emailAddress = admin@magedu.com
verify error:num=19:self signed certificate in certificate chain
verify return:0
---
Certificate chain
 0 s:/C=CN/ST=beijing/O=magedu/OU=devops/CN=www.a.com
   i:/C=CN/ST=beijing/L=beijing/O=magedu/OU=devops/CN=ca.magedu.com/emailAddress=admin@magedu.com
 1 s:/C=CN/ST=beijing/L=beijing/O=magedu/OU=devops/CN=ca.magedu.com/emailAddress=admin@magedu.com
   i:/C=CN/ST=beijing/L=beijing/O=magedu/OU=devops/CN=ca.magedu.com/emailAddress=admin@magedu.com
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIEVDCCAjygAwIBAgIBATANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCQ04x
EDAOBgNVBAgMB2JlaWppbmcxEDAOBgNVBAcMB2JlaWppbmcxDzANBgNVBAoMBm1h
Z2VkdTEPMA0GA1UECwwGZGV2b3BzMRYwFAYDVQQDDA1jYS5tYWdlZHUuY29tMR8w
HQYJKoZIhvcNAQkBFhBhZG1pbkBtYWdlZHUuY29tMB4XDTIyMDcwODA4NTAzOVoX
DTIyMTAxNjA4NTAzOVowVTELMAkGA1UEBhMCQ04xEDAOBgNVBAgMB2JlaWppbmcx
DzANBgNVBAoMBm1hZ2VkdTEPMA0GA1UECwwGZGV2b3BzMRIwEAYDVQQDDAl3d3cu
YS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOjqtHcBRu4eXHuJHJsK
jvdXXoTDhvypv6eDVmTaC3NcRsJ+wwPyqZObL/6rtV4Hdv+DkheH2Wcwmd+1IadJ
pLsIvzbrl2/gZQjEnYMR5NLPaVYgaFHXml2Bg+7BmpRVDzugda7OvTi4wZ1UDH4w
XOCu3hFH/jAzqJ2mFdt0DSchAgMBAAGjezB5MAkGA1UdEwQCMAAwLAYJYIZIAYb4
QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRb
2wcv3YLXfyCTSHRqeyFL06RZmzAfBgNVHSMEGDAWgBRF7cqEG0Umes1bdeLyd0dW
Yif9cTANBgkqhkiG9w0BAQsFAAOCAgEANB1UlpDuXzCthYKK7XXt57lVPb8b0DZs
O6Lyoseo94Hgejf0jN85dcHXyVkA6b5/wrYV1Pre0P/HR8UqK28z2nXe+FJKkxcY
+4x7lMtBUxwnoxE3oZoCiQdcgwPzqdSIs3mT7DoMAkm+a6tvFOZMWSGyc5grx60m
veK5HRtkyec4taOHyOeVk8jY/1FhcaW6+AgDeIyWtQodaqzujw5uwTOr44nlEqAr
+VmbhtdFVN71BbVhbPKbKN9tUye9NyYlJILUxqoFsrv4/KR1Nu4Qy3tGo0IFU6bU
iEchMCGWne8jIoXu3wyH0qZK9rhM6NosSBxNrDzR7GDOqQdb93s4R8C1EBM67QOk
J8eME++O09XAOF1xuWSgcRebHSLzbRm9nyr10qLvInMmzh1nybUL2q0Ml3o/gz/d
boiv0sBR8OYoeOkl/LGLfqXmSAKI0Fqs5Ou9QDp9FoduXXfVG1a92wDsVlb9YjGS
Z8/f96dPrEHu/UBaZMFR8Qc2xGAOqltHCNcKV9ImMTNjbE3gCOSQ1pI8+Mk2B7NX
LsSEhmu74TlzyxCi/Yd6pblHBNa32oLdJ4aItwog829qGJdHsdy504QdJIz5qlSg
RNWAMHJ9t1LQ5YB8I9cdLzOdE/SzJuCRhfJac7kYO0l8+X51Qb9V24G8AGUkwvMx
Ye0leH8L6fU=
-----END CERTIFICATE-----
subject=/C=CN/ST=beijing/O=magedu/OU=devops/CN=www.a.com		<--
issuer=/C=CN/ST=beijing/L=beijing/O=magedu/OU=devops/CN=ca.magedu.com/emailAddress=admin@magedu.com		<--
---
No client certificate CA names sent
Server Temp Key: ECDH, secp521r1, 521 bits
---
SSL handshake has read 3267 bytes and written 441 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: FDA4708AAACE52E1CDB6705120A572AE95382D4FF9DB57FCFECE1A714387938A
    Session-ID-ctx: 
    Master-Key: 12C72C8F2942575EAA97F014BA732FEED31DEFB145D99CE49892010BB0D29DC710050C1D065A4FF2C91483CFDAD96B19
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - c2 83 19 4a 0c 67 02 e2-46 18 70 90 18 0a 56 5e   ...J.g..F.p...V^
    0010 - a4 69 8b c2 ff 99 1d 57-9a c9 56 8e b9 bb ce 5d   .i.....W..V....]
    0020 - 66 b1 43 1f b4 10 39 35-6d 3d e9 41 45 6e eb 87   f.C...95m=.AEn..
    0030 - d5 f8 d5 4e 61 46 97 f8-b0 30 04 7e f0 55 47 f0   ...NaF...0.~.UG.
    0040 - 46 ac 39 93 76 75 0f 30-9c 9a 05 72 60 20 19 68   F.9.vu.0...r` .h
    0050 - 1c 30 e5 0b 28 c5 51 d9-f9 d8 15 7b 87 56 ec 75   .0..(.Q....{.V.u
    0060 - 86 32 09 ae 68 38 12 1b-d5 ee 5d d1 83 65 a0 0a   .2..h8....]..e..
    0070 - ee 21 15 23 5c 69 7c 60-bc 2d 8f ac a5 08 6a 0d   .!.#\i|`.-....j.
    0080 - 55 56 d3 2c 2b 19 8b 5b-f4 3f fd e8 8c 74 89 e1   UV.,+..[.?...t..
    0090 - 3e d4 28 4d 87 9a b1 81-a5 7b af 2a fa 25 36 17   >.(M.....{.*.%6.
    00a0 - ec 0b 60 22 78 87 8b 4c-2c 73 49 95 e0 cb 3b 07   ..`"x..L,sI...;.
    00b0 - 37 0a 56 b4 f1 37 72 7a-5c 2c 1d 0b ed 28 b7 06   7.V..7rz\,...(..

    Start Time: 1657202915
    Timeout   : 300 (sec)
    Verify return code: 19 (self signed certificate in certificate chain)
---

Windows主机测试 在这里插入图片描述 httpd主机:

[root@httpd ssl]# cd ..

[root@httpd conf.d]# vim ssl.conf
...
<VirtualHost _default_:443>		<--

# General setup for the virtual host, inherited from global configuration
#DocumentRoot "/var/www/html"		<--被注释掉了
#ServerName www.example.com:443
...

统一页面

#方法1:修改相应配置
[root@httpd conf.d]# cat /etc/httpd/conf.d/test.conf 
DocumentRoot "/data/html"		<--改为DocumentRoot "/data/asite"
<Directory "/data/html">		<--改为<Directory "/data/asite">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

<virtualhost "*:80">
documentroot /data/asite
servername www.a.com
CustomLog "logs/asite_access_log" combined
<Directory "/data/asite">
    Require all granted
</Directory>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
DeflateCompressionLevel 9
</virtualhost>

<virtualhost "*:80">
documentroot /data/bsite
servername www.b.com
CustomLog "logs/bsite_access_log" combined
<Directory "/data/bsite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:80">
documentroot /data/csite
servername www.c.com
CustomLog "logs/csite_access_log" combined
<Directory "/data/csite">
    Require all granted
</Directory>
</virtualhost>

#重启服务
[root@httpd conf.d]# systemctl restart httpd

Windows主机:测试成功 在这里插入图片描述 httpd主机:

#方法2:
[root@httpd conf.d]# vim ssl.conf 
...
<VirtualHost _default_:443>

# General setup for the virtual host, inherited from global configuration
DocumentRoot "/data/asite"		<--
...

[root@httpd conf.d]# vim /etc/httpd/conf.d/test.conf 
#DocumentRoot "/data/asite"		<--注释掉


[root@httpd conf.d]# systemctl restart httpd

Windows主机:测试成功 在这里插入图片描述

http重定向https

将http请求转发至https的URL 重定向

  • Redirect [status] URL-path URL

status状态:

  • Permanent: 返回永久重定向状态码 301
  • Temp:返回临时重定向状态码302. 此为默认值

Permanent: 返回永久重定向状态码 301

client主机:

[root@centos6 ~]$ curl http://www.a.com
www.a.com
[root@centos6 ~]$ curl http://www.b.com
www.b.com
[root@centos6 ~]$ curl http://www.c.com
www.c.com

http主机:

[root@httpd conf.d]# vim /etc/httpd/conf.d/test.conf 
#DocumentRoot "/data/asite"
<Directory "/data/asite">
    Require all granted
    #Options Indexes FollowSymLinks
    AllowOverride All
</Directory>

<virtualhost "*:80">
documentroot /data/asite
servername www.a.com
CustomLog "logs/asite_access_log" combined
<Directory "/data/asite">
    Require all granted
</Directory>
Redirect Permanent / http://www.b.com/		<--服务a的根时跳转到b主机
</virtualhost>

<virtualhost "*:80">
documentroot /data/bsite
servername www.b.com
CustomLog "logs/bsite_access_log" combined
<Directory "/data/bsite">
    Require all granted
</Directory>
</virtualhost>

<virtualhost "*:80">
documentroot /data/csite
servername www.c.com
CustomLog "logs/csite_access_log" combined
<Directory "/data/csite">
    Require all granted
</Directory>
</virtualhost>


[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl http://www.a.com
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>			<--301 永久跳转
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://www.b.com/">here</a>.</p>
</body></html>

[root@centos6 ~]$ curl -I http://www.a.com
HTTP/1.1 301 Moved Permanently				<--响应码301
Date: Fri, 08 Jul 2022 17:23:20 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/3.4 Python/2.7.5
Location: http://www.b.com/						<--跳转http://www.b.com/		
Content-Type: text/html; charset=iso-8859-1

#-L自动跳转并得到页面信息
[root@centos6 ~]$ curl -L http://www.a.com
www.b.com

Temp:返回临时重定向状态码302. 此为默认值

http主机:

[root@httpd conf.d]# vim /etc/httpd/conf.d/test.conf
...
</Directory>
Redirect Temp  / http://www.b.com/		<--
</virtualhost>
...

[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl -I http://www.a.com
HTTP/1.1 302 Found				<--302
Date: Fri, 08 Jul 2022 17:33:09 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/3.4 Python/2.7.5
Location: http://www.b.com/		<--
Content-Type: text/html; charset=iso-8859-1

[root@centos6 ~]$ curl -L http://www.a.com
www.b.com

实验:http到https的重定向

http主机:

[root@httpd conf.d]# vim /etc/httpd/conf.d/test.conf 
...
</Directory>
Redirect Temp  / https://www.a.com/		<--
</virtualhost>
...

[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl -I http://www.a.com
HTTP/1.1 302 Found			<--302
Date: Fri, 08 Jul 2022 17:41:41 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/3.4 Python/2.7.5
Location: https://www.a.com/			<--
Content-Type: text/html; charset=iso-8859-1

[root@centos6 ~]$ curl -Lk http://www.a.com
www.a.com

http主机:

#还原默认配置
[root@httpd conf.d]# mv test.conf test.conf.bak
[root@httpd conf.d]# vim /etc/httpd/conf.d/ssl.conf
...
<VirtualHost _default_:443>

# General setup for the virtual host, inherited from global configuration
#DocumentRoot "/data/asite/"		<--注释掉后、自动恢复默认
...

[root@httpd conf.d]# vim /etc/httpd/conf/httpd.conf 
...
DocumentRoot "/var/www/html"		<--
...

[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl http://www.a.com
<h1>hello world</h1>
[root@centos6 ~]$ curl -k https://www.a.com
<h1>hello world</h1>
[root@centos6 ~]$ curl -I http://www.a.com
HTTP/1.1 200 OK
Date: Fri, 08 Jul 2022 17:59:01 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/3.4 Python/2.7.5
Last-Modified: Fri, 01 Jul 2022 11:01:38 GMT
ETag: "15-5e2bc4f7425e7"
Accept-Ranges: bytes
Content-Length: 21
Content-Type: text/html; charset=UTF-8

http主机:

[root@httpd conf.d]# vim /etc/httpd/conf/httpd.conf 
...
DocumentRoot "/var/www/html"
Redirect temp / https://www.a.com/		<--跳转
...

[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl -I http://www.a.com
HTTP/1.1 302 Found			<--302
Date: Fri, 08 Jul 2022 18:02:47 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/3.4 Python/2.7.5
Location: https://www.a.com/		<--
Content-Type: text/html; charset=iso-8859-1


[root@centos6 ~]$ curl -Lk http://www.a.com
curl: (47) Maximum (50) redirects followed		<--报错、产生了循环重定向

http主机:

#主要配置信息
[root@httpd conf.d]# vim /etc/httpd/conf/httpd.conf
...
DocumentRoot "/var/www/html"
#Redirect temp / https://www.a.com/		 <--把刚刚写的此行注释掉、此行会循环跳转报错
RewriteEngine on						 <--
RewriteRule ^(/.*)$ https://%{HTTP_HOST}$1 [redirect=302]		<--
...


[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl -Lk http://www.a.com
<h1>hello world</h1>

HSTS

HSTS:HTTP Strict Transport Security

  • 服务器端配置支持HSTS后,会在给浏览器返回的HTTP首部中携带HSTS字段。浏览器获取到该信息后,会将所有HTTP访问请求在内部做307跳转到HTTPS。而无需任何网络过程

HSTS preload list

  • 是Chrome浏览器中的HSTS预载入列表,在该列表中的网站,使用Chrome浏览器访问时,会自动转换成HTTPS。Firefox、Safari、Edge浏览器也会采用这个列表

实现HSTS示例: vim /etc/httpd/conf/httpd.conf Header always set Strict-Transport-Security "max-age=31536000" RewriteEngine on RewriteRule ^(/.*)https:// https://%{HTTP_HOST}1 [redirect=302]

http主机

[root@httpd conf.d]# vim /etc/httpd/conf/httpd.conf 
...
DocumentRoot "/var/www/html"
#Redirect temp / https://www.a.com/
RewriteEngine on
RewriteRule ^(/.*)$ https://%{HTTP_HOST}$1 [redirect=302]
Header always set Strict-Transport-Security "max-age=31536000"		<--实现HSTS
...

[root@httpd conf.d]# systemctl restart httpd

client主机:

[root@centos6 ~]$ curl -I http://www.a.com
HTTP/1.1 302 Found
Date: Sat, 09 Jul 2022 03:40:54 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/3.4 Python/2.7.5
Strict-Transport-Security: max-age=31536000
Location: https://www.a.com/
Content-Type: text/html; charset=iso-8859-1

反向代理功能

:one:启用反向代理 ProxyPass "/" "www.example.com/" ProxyPassReverse "/" "www.example.com/ :two:特定URL反向代理 ProxyPass "/images" "www.example.com/" ProxyPassReverse "/images" www.example.com/ :three:示例: <VirtualHost *> ServerName www.magedu.com ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ </VirtualHost>

Cookie

HTTP 是一种无状态协议。协议自身不对请求和响应之间的通信状态进行保存。 也就是说在 HTTP这个级别,协议对于发送过的请求或响应都不做持久化处理。 这是为了更快地处理大量事务,确保协议的可伸缩性,而特意把 HTTP 协议设计成如此简单的。可是随着 Web 的不断发展,很多业务都需要对通信状态进行 保存。于是引入了 Cookie 技术。使用 Cookie的状态管理Cookie 技术通过在 请求和响应报文中写入 Cookie 信息来控制客户端的状态。Cookie 会根据从服务器端发送的响应报文内的一个叫做 Set-Cookie 的首部字段信息,通知客户端保存Cookie。当下次客户端再往该服务器发送请求时,客户端会自动在请求报 文中加入 Cookie值后发送出去。服务器端发现客户端发送过来的 Cookie 后, 会去检查究竟是从哪一个客户端发来的连接请求,然后对比服务器上的记录,最后得到之前的状态信息

Set-Cookie首部字段

:one:Set-cookie首部字段示例: Set-Cookie: status=enable; expires=Fri, 24 Nov 2017 20:30:02 GMT; path=/; :two:NAME=VALUE 赋予 Cookie 的名称和其值,此为必需项 :three:expires=DATE Cookie 的有效期,若不明确指定则默认为浏览器关闭前为止 :four:path=PATH 将服务器上的文件目录作为Cookie的适用对象,若不指定则默认为文档所在的文件目录 :five:domain=域名 作为 Cookie 适用对象的域名,若不指定则默认为创建Cookie的服务器的域名 :six:Secure 仅在 HTTPS 安全通信时才会发送 Cookie :seven:HttpOnly 加以限制使 Cookie 不能被 JavaScript 脚本访问

setcookic('username','wang');
setcookic('title','cto',time()+3600);			#有效时常3600

实验:源码编辑安装httpd

7主机 安装相应依赖包

[root@centos7 ~]# yum install gcc pcre-devel openssl-devel expat-devel -y

准备源码安装文件

[root@centos7 ~]# cd /data/
[root@centos7 data]# ls
apr-1.7.0.tar.bz2  apr-util-1.6.1.tar.bz2  httpd-2.4.39.tar.bz2

解压缩

[root@centos7 data]# tar xvf apr-1.7.0.tar.bz2 
[root@centos7 data]# tar xvf apr-util-1.6.1.tar.bz2
[root@centos7 data]# tar xvf httpd-2.4.39.tar.bz2 

合并到httpd里/srclib/并改名

[root@centos7 data]# mv apr-1.7.0 httpd-2.4.39/srclib/apr
[root@centos7 data]# mv apr-util-1.6.1 httpd-2.4.39/srclib/apr-util
[root@centos7 data]# ls
apr-1.7.0.tar.bz2  apr-util-1.6.1.tar.bz2  httpd-2.4.39  httpd-2.4.39.tar.bz2

编辑安装

[root@centos7 data]# cd httpd-2.4.39/
[root@centos7 httpd-2.4.39]# ./configure \
> --prefix=/app/httpd24 \		<--安装目录
> --enable-so \
> --enable-ssl \
> --enable-cgi \
> --enable-rewrite \
> --with-zlib \
> --with-pcre \
> --with-included-apr \
> --enable-modules=most \
> --enable-mpms-shared=all \
> --with-mpm=prefork

[root@centos7 httpd24]# make -j 4 && make install

环境变量【基于UDS模式的php-fpm的LAMP到此即可】

[root@centos7 httpd-2.4.39]# cd /app/httpd24/
[root@centos7 httpd24]# echo 'PATH=/app/httpd24/bin:$PATH' > /etc/profile.d/httpd24.sh
#变量生效
[root@centos7 httpd24]# . /etc/profile.d/httpd24.sh 

18主机

[root@caserver ~]# scp /usr/lib/systemd/system/httpd.service 192.168.37.7:/data/

[root@caserver ~]# scp /etc/sysconfig/httpd 192.168.37.7:/etc/sysconfig

7主机

[root@centos7 httpd24]# vim /data/httpd.service 
[Service]
Type=forking
#EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/app/httpd24/bin/httpd $OPTIONS -k start		 <-- 
ExecReload=/app/httpd24/bin/httpd $OPTIONS -k graceful	 <--
[root@centos7 httpd24]# vim /app/httpd24/conf/httpd.conf 
...
User apache		<--
Group apache	<--
...
[root@centos7 httpd24]# systemctl daemon-reload
#设置开机启动 apache 
[root@centos7 httpd24]# vim /etc/rc.local 
...
/app/httpd24//bin/apachectl start
...
#添加权限
[root@centos7 httpd24]# chmod +x /etc/rc.d/rc.local
#重启
[root@centos7 httpd24]# reboot 
#重启后、查看httpd端口是否启动、成功
[root@centos7 ~]# ss -ntl
...
LISTEN      0      128                :::80                             :::* 
...