HTTP协议和web服务技术—Apche

apache介绍与官网

​ 20世纪90年代初,美国国家超级计算机应用中心NCSA开发,1995年开源社区发布apache apache 名字来源,流传最广的解释是(也是最显而易见的):这个名字来自于一个事实:当Apache在 1995年初开发的时候,它是由当时最流行的HTTP服务器NCSA HTTPd 1.3的代码修改而成的,因此 是"一个修补的(a patchy)”服务器。然而,在Apache服务器官方网站的FAQ中是这么解释 的:"Apache这个名字是为了纪念名为Apache的美洲原住民印第安人的一支,众所周知他们拥有高超的 作战策略和无穷的耐性。”贝伦多夫说:"我选择阿帕奇这个名字是取其积极含义。阿帕奇族是最后一个 屈服于美国政府的民族。当时我们担心大公司迟早会参与竞争并‘教化’这块最早的网络之地,所以在我看 来,阿帕奇是个很好的名称,也有人说这个词一语双关-因为正如Apache(与"a patchy"谐音)的名字所 表明的那样,他们确实是在给服务器打补丁。

apache官网

 #apche官网网站:www.apache.org#httpd官网介绍:http://httpd.apache.org/

软件基金会

  • ASF:apache software foundation
  • FSF:Free Software Foundation

apache功能

  • 提供http协议服务
  • 多个虚拟主机:IP、Port、FQDN
  • CGI:Common Gateway Interface,通用网关接口,支持动态程序
  • 反向代理
  • 负载均衡
  • 路径别名
  • 丰富的用户认证机制:basic,digest
  • 支持第三方模块

httpd-2.4新特性

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

apache特性

  • 高度模块化:core + modules
  • DSO:Dynamic shared Object 动态加载/卸载
  • MPM:multi-processing module 多路处理模块

MPM multi-processing module 工作模式

  • prefork:多进程I/O模型,每个进程响应一个请求,CentOS 7 httpd默认模型

    • 一个主进程:生成和回收n个子进程,创建套接字,不响应请求

    • 多个子进程:工作 work进程,每个子进程处理一个请求;系统初始时,预先生成多个空闲进程, 等待请求

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-luWlMiLW-1655366351655)(C:\Users\10163\AppData\Roaming\Typora\typora-user-images\image-20220608095111241.png)]

      Prefork MPM预派生模式,有一个主控制进程,然后生成多个子进程,每个子进程有一个独立的线 程响应用户请求,相对比较占用内存,但是比较稳定,可以设置最大和最小进程数,是最古老的一 种模式,也是最稳定的模式,适用于访问量不是很大的场景

      优点:稳定

      缺点:慢,占用资源,不适用于高并发场景

  • worker:复用的多进程I/O模型,多进程多线程,IIS使用此模型

    • 一个主进程:生成m个子进程,每个子进程负责生个n个线程,每个线程响应一个请求,并发响应 请求:m*n

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-i1v7IQao-1655366351656)(C:\Users\10163\AppData\Roaming\Typora\typora-user-images\image-20220608095259813.png)]

      worker MPM是一种多进程和多线程混合的模型,有一个控制进程,启动多个子进程,每个子进程里面 包含固定的线程,使用线程程来处理请求,当线程不够使用的时候会再启动一个新的子进程,然后在进 程里面再启动线程处理请求,由于其使用了线程处理请求,因此可以承受更高的并发。

      优点:相比prefork 占用的内存较少,可以同时处理更多的请求

      缺点:使用keep-alive的长连接方式,某个线程会一直被占据,即使没有传输数据,也需要一直等待到 超时才会被释放。如果过多的线程,被这样占据,也会导致在高并发场景下的无服务线程可用。(该问 题在prefork模式下,同样会发生)

  • event:事件驱动模型(worker模型的变种),CentOS8 默认模型

    • 一个主进程:生成m个子进程,每个子进程负责生个n个线程,每个线程响应一个请求,并发响应 请求:m*n,有专门的监控线程来管理这些keep-alive类型的线程,当有真实请求时,将请求传递 给服务线程,执行完毕后,又允许释放。这样增强了高并发场景下的请求处理能力

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5KcewZaG-1655366351657)(C:\Users\10163\AppData\Roaming\Typora\typora-user-images\image-20220608095408212.png)]

      event MPM是Apache中最新的模式,2012年发布的apache 2.4.X系列正式支持event 模型. 属于事 件驱动模型(epoll),每个进程响应多个请求,在现在版本里的已经是稳定可用的模式。它和worker 模式很像,最大的区别在于,它解决了keep-alive场景下,长期被占用的线程的资源浪费问题(某 些线程因为被keep-alive,空挂在哪里等待,中间几乎没有请求过来,甚至等到超时)。event MPM中,会有一个专门的线程来管理这些keep-alive类型的线程,当有真实请求过来的时候,将请 求传递给服务线程,执行完毕后,又允许它释放。这样增强了高并发场景下的请求处理能力 event只在有数据发送的时候才开始建立连接,连接请求才会触发工作线程,即使用了TCP的一个 选项,叫做延迟接受连接TCP_DEFER_ACCEPT,加了这个选项后,若客户端只进行TCP连接,不发 送请求,则不会触发Accept操作,也就不会触发工作线程去干活,进行了简单的防攻击(TCP连 接)

      优点:单线程响应多请求,占据更少的内存,高并发下表现更优秀,会有一个专门的线程来管理 keep-alive类型的线程,当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许 它释放

      缺点:没有线程安全控制

      版本限制

      • httpd-2.4:event 稳定版,centos7 以后默认
      • httpd-2.2:event 测试版,centos6 默认

Httpd 安装和相关文件

包安装httpd并启动httpd服务
  • 版本说明:

    • CentOS 7 以上,默认系统是httpd 2.4
    • CentOS 6 版默认为httpd 2.2
    • Ubuntu 18.04 默认 Apache/2.4.29
  • 安装方式

    • 包安装: centos发行版,稳定,建议使用
    • 编译安装
  • 范例:安装httpd-2.4

    #ansible脚本
    - hosts: localhotsremote_user: rootgather_facts: notasks:- name: "软件包安装"yum: name=httpd- name: Modify httpd Configlineinfile: "更改服务端口"path: /etc/httpd/conf/httpd.confregexp: '^Listen'line: 'Listen 8080'- name: Modify html pathlineinfile: "更改路径"path: /etc/httpd/conf/httpd.confregexp: '^DocumentRoot "/var/www/html"'line: 'DocumentRoot "/data/html"'- name:lineinfile:path: /etc/httpd/conf/httpd.confregexp: '<Directory "/var/www/html">'line: '<Directory "/data/html">'- name: "创建文件夹"file: path=/data/html state=directory- name: "复制html文件"copy: src=/root/files/index.html dest=/data/html- name: "启动服务"service:  name=httpd state=started enabled=yes
    #shell脚本
    #!/bin/bash
    ##purpose: 安装apache-2.4,apr-1.7
    #引入本地函数
    . /etc/init.d/functions
    #变量
    Clock_red="echo -e  \033[01;31m"
    Clock_end="\033[0m"
    Pk_path=/var/package
    #check_version:OS版本判断
    function check_version()
    {Version=$(lsb_release -a|awk '{for(i=1;i<=NR;i++)if($i ~ /CentOS/){print $i}}')case $Version in Centos|Redhat)return 1;;Ubuntu)return 2;;*)"$Clock_red"warning:不支持该系统"$Clock_end"exit 0;;esac
    }
    function install_apache()
    {case $? in1)yum -y install httpd && systemctl enable --now httpd && action "httpd安装完成";;2)apt install apache2 -y && systemctl start apache2 && echo "安装完成";;esac
    }
    check_version
    install_apache
    
httpd-2.4 相关文件
配置文件
  • /etc/httpd/conf/httpd.conf 主配置文件
  • /etc/httpd/conf.d/*.conf 子配置文件
  • etc/httpd/conf.d/conf.modules.d/ 模块加载的配置文件

配置检查语法:httpd -t 或者 apache2 -t

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

日志文件目录

  • /var/log/httpd

    • access_log:访问日志
    • error_log:错误日志
帮助文档包
  • httpd-manual
httpd配置文件的组成
主要组成
  • Global Environment
  • Main server configuration
  • virtual host
配置文件格式
directive value

格式说明:

  • directive 不区分字符大小写
  • value 为路径时,是否区分大小写,取决于文件系统
配置文件语法检查
apachectl configtest
apachectl -t
httpd -t
编译安装 httpd-2.4

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Mog5ob1r-1655366351657)(C:\Users\10163\AppData\Roaming\Typora\typora-user-images\image-20220608112836883.png)]

APR:Apache portable Run-time libraries,Apache可移植运行库,主要为上层的应用程序提供一个可 以跨越多操作系统平台使用的底层支持接口库。在早期的Apache版本中,应用程序本身必须能够处理各 种具体操作系统平台的细节,并针对不同的平台调用不同的处理函数随着Apache的进一步开发, Apache组织决定将这些通用的函数独立出来并发展成为一个新的项目。这样,APR的开发就从Apache 中独立出来,Apache仅仅是使用 APR而已。目前APR主要还是由Apache使用,由于APR的较好的移植 性,因此一些需要进行移植的C程序也开始使用APR,开源项目:比如用于服务器压力测试的Flood loader tester

项目站点:http://httpd.apache.org/test/flood

说明:安装httpd-2.4,依赖于apr-1.4+,apr-util-1.4+

官方源码包发布站点

  • apr包下载:http://archive.apache.org/dist/apr/
  • httpd包下载:http://archive.apache.org/dist/httpd
  • 查看配置文件:rpm -qc (需用rpm方式安装)

编译过程

1.安装关联工具:yum -y install gcc make pcre-devel openssl-devel expat-devel
2.下载httpd编译包:wget https://mirrors.tuna.tsinghua.edu.cn/apache/httpd/httpd-2.4.54.tar.bz2 --no-check-certificate
3.下载apr编译包:wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.bz2 --no-check-certificate
4.下载apr-util工具编译包:wget https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-util-1.6.1.tar.bz2 --no-check-certificate
5.解压二进制包:
tar -xvf httpd-2.4.54
tar -xvf *.tar.bz2 -C httpd-2.4.54/srclib/
mv httpd-2.4.54/srclib/apr-1.7.0 httpd-2.4.54/srclib/apr
mv httpd-2.4.54/srclib/apr-util-1.6.1 httpd-2.4.54/srclib/apr-util
6.编译安装
cd httpd-2.4.54/
./configure \
--prefix=/apps/httpd \
--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
make -j 4 && make install
7.创建用户:
useradd -s /sbin/nologin -r apache
8.指定httpd运行用户
sed -ri  "/^User.*/s/daemon/apache/" /apps/httpd/conf/httpd.conf
sed -ri  "/^Group.*/s/daemon/apache/" /apps/httpd/conf/httpd.conf
9.修改环境变量
echo 'PATH=/apps/httpd/bin:$PATH' > /etc/profile.d/httpd.sh
. /etc/profile.d/httpd.sh
10.配置man帮助
echo 'MANDATORY_MANPATH /apps/httpd/man' >> /etc/man_db.conf11.创建service unit文件
vim /usr/lib/systemd/system/httpd24.service
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)
[Service]
Type=forking
#EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/apps/httpd/bin/apachectl start
#ExecStart=/apps/httpd/bin/httpd $OPTIONS -k start
ExecReload=/apps/httpd/bin/apachectl graceful
#ExecReload=/apps/httpd/bin/httpd $OPTIONS -k graceful
ExecStop=/apps/httpd/bin/apachectl stop
KillSignal=SIGCONT
PrivateTmp=true
[Install]
WantedBy=multi-user.target12.启动服务,并设置开机启动
systemctl daemon-reload
systemctl enable --now httpd.service

编译安装shell脚本

#!/bin/bash
##purpose: 编译安装apache-2.4.X,apr-1.7,apr-util-1.6.1
#引用系统变量
. /etc/init.d/functions
#变量
Clock_red="echo -e  \033[01;31m"
Clock_end="\033[0m"
Pk_path=/var/package
PKname=(
httpd-2.4.53
apr-1.7.0
apr-util-1.6.1
)
suffix=tar.bz2
httpd_url=http://archive.apache.org/dist/httpd
apr_url=https://mirrors.tuna.tsinghua.edu.cn/apache/apr
#apr_url=http://archive.apache.org/dist/apr/#-------------------------------------------代码主体-------------------------------------------#
##check_version:OS版本判断
function check_version()
{if [  "$(rpm -qa |grep redhat-lsb-core-4.1-27.el7.centos.1.x86_64)" ];thenVersion=$(lsb_release -a|awk '{for(i=1;i<=NR;i++)if($i ~ /CentOS/){print $i}}')case $Version in Centos)return 1;;redhat)return 2;;Ubuntu)return 3;;*)"$Clock_red"Warning:不支持该系统"$Clock_end"exit 0;;esac
elseVersion=$(awk -F'"' '/^ID=/{print $2}' /etc/os-release)case $Version in CentOS)return 1;;redhat)return 2;;Ubuntu)return 3;;*)"$Clock_red"warning:不支持该系统"$Clock_end"exit 0;;esacfi
}#源码编译包下载
function get_url()
{#判断下载路径是否有对应文件for ((i=0;i<=$((${#PKname[@]}-1));i++));doif [ ! -f "$Pk_path"/"${PKname[$i]}" ];then#下载软件包wget -P "$Pk_path"  "$httpd_url"/"${PKname[$i]}"."$suffix" --no-check-certificate &> /dev/null || \wget -P "$Pk_path"  "$apr_url"/"${PKname[$i]}"."$suffix" --no-check-certificate &> /dev/null || \action "Warning:下载失败,请注意网络配置" false && exit 1fidone
}#解压编译包到指定路径
function uncompress()
{cd "$Pk_path" ||exit 1
for((i=0;i<=$((${#PKname[@]}-1));i++));do#这里要保证httpd的编译包下标为0,不然会逻辑错误,会报错;if [[ "${PKname[$i]}.${suffix}" =~ ^httpd-* ]];thentar -xvf "${PKname[$i]}"."$suffix" -C "$Pk_path"elsetar -xvf "${PKname[$i]}"."$suffix" -C "$Pk_path/${PKname[0]}/srclib/" || exit 1fi
done}#编译安装与用户创建,MPM模式是prefork
function makeinstall()
{cd "$Pk_path"/"${PKname[0]}" || exit 1
./configure \
--prefix=/apps/httpd \
--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
#编译安装
make -j 4 && make install || exit 3
#创建用户
id apache || useradd -s /sbin/nologin -r apache
#修改配置文件,指定用户
if [ -f /apps/httpd/conf/httpd.conf ];thensed -ri  "/^User.*/s/daemon/apache/" /apps/httpd/conf/httpd.confsed -ri  "/^Group.*/s/daemon/apache/" /apps/httpd/conf/httpd.conf
fi
#修改环境变量
echo 'PATH=/apps/httpd/bin:$PATH' > /etc/profile.d/httpd.sh &&  sh /etc/profile.d/httpd.sh
#配置man帮助文档
echo 'MANDATORY_MANPATH /apps/httpd/man' >> /etc/man_db.conf
#配置service unit文件
if [ ! -f /usr/lib/systemd/system/httpd.conf ];then
tee /usr/lib/systemd/system/httpd.conf <<EOF
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)
[Service]
Type=forking
ExecStart=/apps/httpd/bin/apachectl start
ExecReload=/apps/httpd/bin/apachectl graceful
ExecStop=/apps/httpd/bin/apachectl stop
KillSignal=SIGCONT
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
fi
#启动服务,并设置开机启动
systemctl daemon-reload
systemctl enable --now httpd.service && action "httpd 配置完成"
}check_version
get_url
uncompress
makeinstall

编译安装yaml脚本

#变量文件-httpd_varsfile.ymlURL:-  https://mirrors.tuna.tsinghua.edu.cn/apache/httpd-  https://mirrors.tuna.tsinghua.edu.cn/apache/apr-  https://mirrors.tuna.tsinghua.edu.cn/apache/aprPkname:- httpd-2.4.46- apr-1.7.0- apr-util-1.6.1download_dir: /usr/local/srcinstall_dir: /apps/httpd
#playbook
#!/usr/bin/ansible-playbook
---
# This is a playbook file
# purpose: Compile the installation HTTPS
- hosts: webservsremote_user: rootvars_file:- /root/Date/vars/httpd_varsfile.ymltasks:
# 任务一:环境准备-包下载- name: "依赖包安装"yum: name=gcc,make,pcre-devel,openssl-devel,expat-devel,bzip2 state=installed- name: "包下载包"get_url: url={{ item.0 }}/{{ item.1 }}.{{ suffix }} dest={{ download_dir }} validate_certs=nowith_together:- "{{ URL }}"- "{{ Pkname }}"delegate_to: localhost
# 任务二: 解压安装- name: "解压包至对端"unarchive: src="/{{ download_dir }}/{{ item.0 }}.{{ suffix }} dest={{ download_dir }} owner=root remote_src=yeswith_nested:- {{ Pkname }}
# 任务三:编译安装软件- name: "移动apr目录到指定目录"shell: chdir={{ download_dir }}   mv {{ Pkname.1 }} {{ download_dir }}/{{ Pkname.0 }}/srclib/apr- name: "移动apr_util目录到指定目录" shell: chdir={{ download_dir }}   mv {{ Pkname.2 }} {{ download_dir }}/{{ Pkname.0 }}/srclib/apr-util- name: "编译安装httpd"shell: chdir={{ download_dir }}/{{ Pkname.0 }} ./configure --prefix={{ install_dir }} --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 &&  make -j {{ ansible_processor_vcpus }} && make install- name: "创建用户组"group: name=apache gid=80 system=yes- name: "创建用户"user: name=apache uid=80 group=apache shell=/sbin/nologin system=yes create_home=no home={{ install_dir }}/conf/httpd- name: set httpd userlineinfile: path={{ install_dir }}/conf/httpd.conf regexp='^User' line='User apache'- name: set httpd grouplineinfile: path={{ install_dir }}/conf/httpd.conf regexp='^Group' line='Group apache'- name: set variable PATHshell: echo PATH={{ install_dir }}/bin:$PATH >> /etc/profile.d/httpd.sh- name: "通过模板生成httpd配置文件"template: src=./httpd.service.j2 dest=/usr/lib/systemd/system/httpd.service- name: "启动服务,且开机生效"service: name=httpd state=started enabled=yes

HTTPD常见配置

指令学习官网:https://httpd.apache.org/docs/2.4/mod/quickreference.html

指定服务器名称:ServerName
http -t在检查语法时会出现AH005578,原因是未指定主机名称
解决方法:也可以修改为自定义主机名称
修改原有:sed -ri "s/^#(Server.*)/\1/" /apps/httpd/conf/httpd.conf
后面追加:sed -ri "/^#ServerName/a ServerName www.Deming.org:8001" /apps/httpd/conf/httpd.conf
包含其它配置文件:Include和IncludeOptional

指令

Include file-path|directory-path|wildcard
IncludeOptional file-path|directory-path|wildcard

说明:

  • Include和IncludeOptional功能相同,都可以包括其它配置文件
  • 但是当无匹配文件时,include会报错,IncludeOptional会忽略错误
配置文件中包含Include:
[root@xiangdeming ~23:36]#grep -i Include /apps/httpd/conf/httpd.conf
Include conf.modules.d/*.conf
#LoadModule include_module modules/mod_include.so#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
# Possible values include: debug, info, notice, warn, error, crit,# If you include a trailing / on /webpath then the server will# To parse .shtml files for server-side includes (SSI):# (You will also need to add "Includes" to the "Options" directive.)#AddOutputFilter INCLUDES .shtml
IncludeOptional conf.d/*.conf路径定义指令:ServerRoot
[root@xiangdeming ~23:44]#grep -Ei "^ServerRoot" /apps/httpd/conf/httpd.conf
ServerRoot "/apps/httpd"模块存放路径:"$ServerRoot"/conf.modules.d(如果是编译安装且未编译该路径则为modules下)
配置文件存放路径:"$ServerRoot"/conf.d(如果是编译安装且未编译该路径则为/conf/extra)
监听的IP和Port:Listen
生成额外的配置文件:(需要保证配置文件中有includeOptional xxx/*.conf)
grep -Ei "^IncludeOptiona" || echo "IncludeOptional conf/extra/Test.conf" >> /apps/conf/httpd.conf
echo "listen 8001"/apps/conf/extra/Tess.conf
!sys修改原有配置文件
sed -ri "/^Listen/s/80/8001/" /apps/httpd/conf/httpd.conf
sed -rn "/^Listen/a Listen 8001" /apps/httpd/conf/httpd.conf

隐藏服务器版本信息:ServerTokens

常用参数对应关系

  • ServerTokens Prod[uctOnly] Server: Apache
  • ServerTokens Major: Server: Apache/2
  • ServerTokens Minor: Server: Apache/2.0
  • ServerTokens Min[imal]: Server Apache/2.0.41
  • ServerTokens OS: Server: Apache/2.0.41 (Unix)
  • ServerTokens full: all(全部显示)
查看版本信息:
[root@web-0aadc460 ~16:32]$curl -I 192.168.213.100
HTTP/1.1 200 OK
Date: Wed, 15 Jun 2022 16:32:29 GMT
Server: Apache/2.4.54 (Unix)
Last-Modified: Mon, 11 Jun 2007 18:53:14 GMT
ETag: "2d-432a5e4a73a80"
Accept-Ranges: bytes
Content-Length: 45
Content-Type: text/html
#添加ServerTokens指令
grep -i ServerTokens ../httpd.conf && echo "ServerTokens Prod" >> Test.conf
#添加原文件
grep -i ServerTokens ../httpd.conf && echo "ServerTokens Prod" >> ../httpd.conf[root@web-0aadc460 ~16:33]$curl -I 192.168.213.100
HTTP/1.1 200 OK
Date: Wed, 15 Jun 2022 16:39:13 GMT
Server: Apache
Last-Modified: Mon, 11 Jun 2007 18:53:14 GMT
ETag: "2d-432a5e4a73a80"
Accept-Ranges: bytes
Content-Length: 45
Content-Type: text/html

禁止错误网页版本泄露:ServerSignature

常用参数对应关系

  • ServerSignature On
  • ServerSignature off
  • ServerSignature EMail

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

#该值默认关闭
#开启后
echo -e ServerAdmin root@xiangdeming.com"\n"ServerSignature off >> Test.conf
#错误页面会显示邮箱与IP和端口(关闭则只显示404)
[root@web-0aadc460 ~16:44]$curl -i 192.168.213.100/xxx
HTTP/1.1 404 Not Found
Date: Wed, 15 Jun 2022 16:45:08 GMT
Server: Apache
Content-Length: 305
Content-Type: text/html; charset=iso-8859-1<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache Server at <a href="mailto:root@xiangdeming.com">192.168.213.100</a> Port 8001</address>
</body></html>
#关闭该指令
[root@xiangdeming extra00:46]#echo -e ServerAdmin root@xiangdeming.com"\n"ServerSignature off
#只显示404,不显示任何别的信息
[root@web-0aadc460 ~16:49]$curl -i 192.168.213.100/xxx
HTTP/1.1 404 Not Found
Date: Wed, 15 Jun 2022 16:50:55 GMT
Server: Apache
Content-Length: 196
Content-Type: text/html; charset=iso-8859-1<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>

持久链接:KeepAlive

  • Persistent Connection:连接建立,每个资源获取完成后不会断开连接,而是继续等待其它的请求完
    成,默认开启持久连接

  • 断开条件:

    时间限制:以秒为单位, 默认5s,httpd-2.4 支持毫秒级
    请求数量: 请求数达到指定值,也会断开
    

    副作用:对并发访问量大的服务器,持久连接会使有些请求得不到响应
    折衷:使用较短的持久连接时间

持久连接相关指令常用参数对应关系

  • KeepAlive On
  • KeepAlive Off
KeepAlive On|Off
KeepAliveTimeout 15 #连接持续15s,可以以ms为单位,默认值为5s
MaxKeepAliveRequests 500 #持久连接最大接收的请求数,默认值100
关闭持久连接(持久连接默认开启)
echo KeepAlive Off >> Test.conf
使用telnet测试(获取后直接返回结果,然后中断连接)
[root@web-0aadc460 ~17:05]$telnet 192.168.213.100 80
Trying 192.168.213.100...
Connected to 192.168.213.100.
Escape character is '^]'.
GET /index.html HTTP/1.1
host: 1.1.1.1
HTTP/1.1 408 Request Timeout
Date: Wed, 15 Jun 2022 17:06:13 GMT
Server: Apache
Content-Length: 221
Connection: close
Content-Type: text/html; charset=iso-8859-1<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>408 Request Timeout</title>
</head><body>
<h1>Request Timeout</h1>
<p>Server timeout waiting for the HTTP request from the client.</p>
</body></html>
Connection closed by foreign host.开启持久连接,并设置持续时间为15秒
echo -e KeepAlive On"\n"KeepAliveTimeout 15 >> Test.conf
使用telnet测试(可以在15秒内反复获取网页)

DSO(Dynamic Shared Object)

名词解释:Dynamic Shared Object,加载动态模块配置,不需重启即生效

  • 默认动态模块所在路径: /usr/lib64/httpd/modules/

  • 主配置 /etc/httpd/conf/httpd.conf 文件中指定加载模块配置文件:

    ServerRoot "/etc/httpd"
    Include conf.modules.d/*.conf
    

配置指定实现模块加载格式:

LoadModule <mod_name> <mod_path>
  • 模块文件路径可使用相对路径:/etc/httpd/modules(默认)

  • 模块文件路径可使用相对加载路径:/etc/httpd/conf.modules.d(默认)

  • 编译未指定模块文件路径可使用相对路径:$ServerRoot/httpd/modules

  • 编译未指定模块文件路径可使用相对加载路径:$ServerRoot/httpd/conf/httpd.conf(主配置文件中指定加载)

    若需要修改可以添加“Include conf.modules.d/*.conf”的方式实现

  • 查看已经加载的动态模块文件:httpd -M

    Loaded Modules:core_module (static)so_module (static)http_module (static)mpm_prefork_module (shared)authn_file_module (shared)authn_core_module (shared)authz_host_module (shared)authz_groupfile_module (shared)authz_user_module (shared)authz_core_module (shared)access_compat_module (shared)auth_basic_module (shared)reqtimeout_module (shared)filter_module (shared)mime_module (shared)log_config_module (shared)env_module (shared)headers_module (shared)setenvif_module (shared)version_module (shared)unixd_module (shared)status_module (shared)autoindex_module (shared)dir_module (shared)alias_module (shared)
    
  • 查看已经加载的静态模块文件:httpd -l

    只能在编译的时候写入,替换只能重新编译
    Compiled in modules:core.cmod_so.chttp_core.c
    

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

httpd 支持三种MPM工作模式:prefork, worker, event

切换使用的MPM:

#RPM安装时修改
查看
httpd -M |grep -i mpm
修改
vim /etc/httpd/conf.modules.d/00-mpm.conf
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
LoadModule mpm_event_module modules/mod_mpm_event.so#编译安装修改:
查看
httpd -M |grep -i mpm
查看进程(prefork)
[root@xiangdeming conf02:11]#pstree -p 41606
httpd(41606)─┬─httpd(41607)├─httpd(41608)├─httpd(41609)├─httpd(41610)├─httpd(41611)├─httpd(41612)└─httpd(41621)
修改为event模式i
sed -ri "s/^(LoadModule mpm.*)/#\1/" httpd.conf
sed -ri "/LoadModule mpm_event.*/s/#//" httpd.conf
重启服务
!sys
查看(event)
httpd(42272)─┬─httpd(42273)─┬─{httpd}(42279)│              ├─{httpd}(42300)│              ├─{httpd}(42303)│              ├─{httpd}(42306)│              ├─{httpd}(42308)│              ├─{httpd}(42310)│              ├─{httpd}(42312)│              ├─{httpd}(42313)│              ├─{httpd}(42314)│              ├─{httpd}(42315)│              ├─{httpd}(42316)│              ├─{httpd}(42317)│              ├─{httpd}(42318)│              ├─{httpd}(42319)│              ├─{httpd}(42320)│              ├─{httpd}(42321)│              ├─{httpd}(42322)│              ├─{httpd}(42323)│              ├─{httpd}(42324)│              ├─{httpd}(42325)│              ├─{httpd}(42326)│              ├─{httpd}(42327)│              ├─{httpd}(42328)│              ├─{httpd}(42329)│              ├─{httpd}(42330)│              └─{httpd}(42331)├─httpd(42274)─┬─{httpd}(42278)│              ├─{httpd}(42280)│              ├─{httpd}(42281)│              ├─{httpd}(42282)│              ├─{httpd}(42283)│              ├─{httpd}(42284)│              ├─{httpd}(42285)│              ├─{httpd}(42288)│              ├─{httpd}(42289)│              ├─{httpd}(42290)│              ├─{httpd}(42291)│              ├─{httpd}(42292)│              ├─{httpd}(42293)│              ├─{httpd}(42294)│              ├─{httpd}(42295)│              ├─{httpd}(42296)│              ├─{httpd}(42297)│              ├─{httpd}(42298)│              ├─{httpd}(42299)│              ├─{httpd}(42301)│              ├─{httpd}(42302)│              ├─{httpd}(42304)│              ├─{httpd}(42305)│              ├─{httpd}(42307)│              ├─{httpd}(42309)│              └─{httpd}(42311)└─httpd(42275)─┬─{httpd}(42287)├─{httpd}(42332)├─{httpd}(42333)├─{httpd}(42334)├─{httpd}(42335)├─{httpd}(42336)├─{httpd}(42337)├─{httpd}(42338)├─{httpd}(42339)├─{httpd}(42340)├─{httpd}(42341)├─{httpd}(42342)├─{httpd}(42343)├─{httpd}(42344)├─{httpd}(42345)├─{httpd}(42346)├─{httpd}(42347)├─{httpd}(42348)├─{httpd}(42349)├─{httpd}(42350)├─{httpd}(42351)├─{httpd}(42352)├─{httpd}(42353)├─{httpd}(42354)├─{httpd}(42355)└─{httpd}(42356)
prefork 模式相关的配置
StartServers 100
MinSpareServers 50#最少空闲进程
MaxSpareServers 80#最大空闲进程
ServerLimit 2560 #最多进程数,最大值 20000
MaxRequestWorkers 2560 #最大的并发连接数,默认256
MaxConnectionsPerChild 4000 #子进程最多能处理的请求数量。在处理MaxRequestsPerChild 个
请求之后,子进程将会被父进程终止,这时候子进程占用的内存就会释放(为0时永远不释放)
MaxRequestsPerChild 4000 #从 httpd.2.3.9开始被MaxConnectionsPerChild代替
worker和event 模式相关的配置
ServerLimit 16 #最多worker进程数的可配置数量的上限
StartServers 10 #启动时创建的子服务器进程数
MaxRequestWorkers 150 #同时被处理的最大连接数
MinSpareThreads 25#最少空闲进程
MaxSpareThreads 75#最大空闲进程
ThreadsPerChild 25 #每个子进程创建的线程数

定义Main server的文档页面路径:DocumentRoot

注意事项

  • DocumentRoot指向的路径为URL路径的起始位置

  • /path 必须显式授权后才可以访问

  • DocumentRoot指向的路径为URL路径的起始位置

  • /path 必须显式授权后才可以访问

#rpm包安装默认路径为:/var/www/html
[root@web-0aadc460 conf18:28]$grep -i "^DocumentRoot" httpd.conf
DocumentRoot "/var/www/html"
#编译安装默认路径为:$ServerRoot/htdocs
[root@xiangdeming conf02:31]#grep -i "^DocumentRoot" httpd.conf
DocumentRoot "/apps/httpd/htdocs#修改DocumentRoot时需要连后面的运行访问一并修改
[root@xiangdeming conf02:31]#grep -A1 -i "^DocumentRoot" httpd.conf
DocumentRoot "/apps/httpd/htdocs"
<Directory "/apps/httpd/htdocs">
#修改
sed -ri  "s/\/apps\/httpd\/htdocs/\/var\/www\/html/g" httpd.conf
#修改DocumentRoot后也可以添加进扩展配置文件中
echo "DocumentRoot \"/apps/httpd/htdocs\"" >> Test.conf
echo -e \<Directory \"/var/www/html\"\> "\n \
>Require all granted "\n"\
>\<\/Directory\> >> Test.conf#重启服务
!sys

定义站点默认主页面文件:DirectoryIndex

[root@xiangdeming extra02:54]#grep -i "^ *DirectoryIndex" ../httpd.conf DirectoryIndex index.html

定义路径别名:alias

  • 实现路径别名,在访问一个路径时指向另外一个真实路径

alias格式:

Alias /URL/ "/PATH/"
#修改额外配置文件,增加允许访问目录(修改原文件也一样,直接追加在文末即可)
echo -e \<Directory \"/var/www/html\"\> "\n \
>Require all granted "\n"\
>\<\/Directory\> >> Test.conf
#增加别名配置var/www/html
echo "alias /blog /var/www/html" >> Test.conf

可实现访问控制的资源<XX>与<\XX>

常用的资源访问控制

  • 基于目录访问控制

    • Directory

      格式:
      <Directory "/var/www/html">
      ...(Options指令)
      </Directory>
      
  • 基于文件访问控制

    • Files

      格式:
      <Files "/var/www/html/index.html|png|...">
      ...(Options指令)
      </Files>
      
  • 基于扩展正则表达式

    • FilesMatch

      格式:
      <FilesMatch ".+\.(gif|jpe?g|png)$">
      ...(Options指令)
      </FilesMatch>
      

针对目录和URL实现访问控制:Options

Options指令说明
  • 后跟1个或多个以空白字符分隔的选项列表, 在选项前的+,- 表示增加或删除指定选项

常见选项

  • Indexes:指明的URL路径下不存在与定义的主页面资源相符的资源文件时,返回索引列表给用户
  • FollowSymLinks:允许访问符号链接文件所指向的源文件
  • None:全部禁用
  • All: 全部允许
#创建link文件 link.txt
ln -s /etc/fstab /var/www/html/link.txt
#这里是因为我设置了别名,且设置在额外的conf配置文件中设置的额外的监听
[root@web-0aadc460 ~22:56]$curl http://192.168.213.100:8080/blog/link.txt#
# /etc/fstab
# Created by anaconda on Mon Jan 17 04:40:08 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
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=7e5c2c17-aa16-4013-8478-35b47290ca5e /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
/dev/cdrom /mnt/cdrom   iso9660 defaults 0 0
/dev/cdrom /var/www/html/Centos/7/os/x86_64/ iso9660 defaults 0 0#关闭主页面
[root@xiangdeming extra23:14]#mv /var/www/html/index.html /var/www/html/index
#尝试访问,提示无权限访问(编译安装没有测试页面,若是rpm安装则需要在conf.d中修改welcome.conf文件)
[root@web-0aadc460 ~23:12]$curl http://192.168.213.100/blog
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://192.168.213.100/blog/">here</a>.</p>
</body></html>
#增加Options Indexes指令
sed -ri '/^<Directory.*/a\    Options indexes FollowSymLinks' Test.conf
#再次尝试访问,获取到/var/www/html下文件列表
[root@web-0aadc460 ~23:23]$curl http://192.168.213.100/blog/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html><head><title>Index of /blog</title></head><body>
<h1>Index of /blog</h1>
<ul><li><a href="/"> Parent Directory</a></li>
<li><a href="Centos/"> Centos/</a></li>
<li><a href="index"> index</a></li>
<li><a href="index1.html"> index1.html</a></li>
<li><a href="index2.html"> index2.html</a></li>
<li><a href="link.txt"> link.txt</a></li>
</ul>
</body></html>
#如果需要去除某功能可以增加-号,如下所示:(这里去除了对link文件的支持)
<Directory /var/www/html>Require all granted Options indexes -FollowSymLinks
</Directory>
AllowOverride指令说明
  • 与访问控制相关的哪些指令可以放在指定目录下的.htaccess(由AccessFileName 指令指定,AccessFileName .htaccess 为默认值)文件中,覆盖之前的配置指令,只对语句有效

常见选项:

  • AllowOverride All: .htaccess中所有指令都有效
  • AllowOverride None: .htaccess 文件无效,此为httpd 2.3.9以后版的默认值
  • AllowOverride AuthConfig: .htaccess 文件中,除了AuthConfig 其它指令都无法生效
#修改额外配置文件Test.conf,将Options指令替换为AllowOverride all指令
sed -ri "s/Options indexes FollowSymLinks/AllowOverride all/" Test.conf
#在/var/www/html($DocumentRoot或者额外配置文件的alias真实路径)
echo "Options indexes FollowSymLinks" > /var/www/html/.htaccess
#重启服务后,再次访问
[root@web-0aadc460 ~23:28]$curl http://192.168.213.100/blog/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html><head><title>Index of /blog</title></head><body>
<h1>Index of /blog</h1>
<ul><li><a href="/"> Parent Directory</a></li>
<li><a href="Centos/"> Centos/</a></li>
<li><a href="index"> index</a></li>
<li><a href="index1.html"> index1.html</a></li>
<li><a href="index2.html"> index2.html</a></li>
<li><a href="link.txt"> link.txt</a></li>
</ul>
</body></html>#.ht开头的文件默认被禁止访问
[root@xiangdeming extra00:00]#grep -A2 "ht\*" ../httpd.conf
<Files ".ht*">Require all denied
</Files>

基于客户端 IP 地址实现访问控制:Require

针对各种资源,可以基于以下两种方式的访问控制:

  • 客户端来源地址
  • 用户账号

基于客户端的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:指定域名下的所有主机

黑名单:

  • 不能有失败,至少有一个成功匹配才成功,即失败优先
#对额外配置文件Test.conf增加特定主机的访问拒绝
sed -ri "/AllowOverride all/a\    Require not ip 192.168.213.122" Test.con
[root@xiangdeming extra21:53]#cat Test.conf
#Listen 8080
ServerTokens Prod
ServerAdmin root@xiangdeming.com
ServerSignature off
KeepAlive On
KeepAliveTimeout 15
<Directory /var/www/html>AllowOverride all<RequireALL>Require all grantedRequire not ip 192.168.213.122</RequireALL>
</Directory>
alias /blog /var/www/html/
#尝试访问,可以访问默认index,但无法访问alise
[root@web-0aadc460 ~21:56]$curl 192.168.213.100
<html><body><h1>It works!</h1></body></html>
[root@web-0aadc460 ~21:56]$curl 192.168.213.100/blog
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://192.168.213.100/blog/">here</a>.</p>
</body></html>

白名单:

  • 多个语句有一个成功,则成功,即成功优先
#白名单写法
<Directory /var/www/html>AllowOverride all<RequireALL>Require all deniedRequire ip 192.168.213.122</RequireALL>
</Directory>

日志设置:Errorlog与Customlog

httpd有两种日志类型

错误日志:Errorlog

  • RPM安装路径:/var/log/httpd/errorl_log

  • 编译安装默认路径:编译路径/logs/errorl_log

    • 记录的内容:

      • 记录主机的访问过程,会有具体时间,客户端IP地址,报文指令,相应编码,浏览器的版本,访问的资源等;
      • 修改访问日志模式:CustomLog
      • LogFormat指令参数解释(与访问日志一致)
        • 官方文档:https://httpd.apache.org/docs/2.4/mod/core.html#errorlogformat
  • 访问日志:Customlog

    • RPM安装路径:/var/log/httpd/access_log

    • 编译安装默认路径:编译路径/logs/access_log

      • 记录的内容:

        • 记录主机的访问过程,会有具体时间,客户端IP地址,报文指令,相应编码,浏览器的版本,访问的资源等;

          • 修改访问日志模式:CustomLog

            [root@xiangdeming conf22:18]#grep -E -A20 "^<IfModule log_config_module>" httpd.conf
            <IfModule log_config_module>## The following directives define some format nicknames for use with# a CustomLog directive (see below).#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combinedLogFormat "%h %l %u %t \"%r\" %>s %b" common<IfModule logio_module># You need to enable mod_logio.c to use %I and %OLogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio</IfModule>## The location and format of the access logfile (Common Logfile Format).# If you do not define any access logfiles within a <VirtualHost># container, they will be logged here.  Contrariwise, if you *do*# define per-<VirtualHost> access logfiles, transactions will be# logged therein and *not* in this file.#CustomLog "logs/access_log" common
            
          • LogFormat指令参数解释

            • 官网地址:https://httpd.apache.org/docs/2.4/mod/mod_log_config.html#logformat
            LogFormat 定义日志显示内容
            %h #客户端IP地址
            %l #远程用户,启用mod_ident才有效,通常为减号"-”
            %u #验证(basic,digest)远程用户,非登录访问时,为一个减号"-”
            %t #服务器收到请求时的时间
            %r #First line of request,即表示请求报文的首行;记录了此次请求的"方法”,"URL”以及协
            议版本
            %>s #响应状态码
            %b #响应报文的大小,单位是字节;不包括响应报文http首部
            %{Referer}i #请求报文中首部"referer”的值;即从哪个页面中的超链接跳转至当前页面的
            %{User-Agent}i #请求报文中首部"User-Agent”的值;即发出请求的应用程序
            %{VARNAME}i #发送到的请求中VARNAME:标题行(多行)的内容
            
            #自定义logFormat并修改时间格式
            sed -ri '/(.*LogFormat.*)%t(.* )common$/a\    LogFormat "%h %l %u \\"%{%F %T}t\\" \\"%r\\" %>s %b" Test' httpd.conf
            sed -ri "s/(.*CustomLog.* common$)/#\1/" httpd.conf
            sed -ri '/^#.*common$/a\    CustomLog "logs/access_log" Test' httpd.conf
            #尝试访问
            [root@web-0aadc460 logs15:01]$curl 192.168.213.100:80/blog/
            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
            <html><head><title>Index of /blog</title></head><body>
            <h1>Index of /blog</h1>
            <ul><li><a href="/"> Parent Directory</a></li>
            <li><a href="Centos/"> Centos/</a></li>
            <li><a href="index"> index</a></li>
            <li><a href="index1.html"> index1.html</a></li>
            <li><a href="index2.html"> index2.html</a></li>
            </ul>
            </body></html>
            #查看日志
            [root@xiangdeming extra23:00]#tail -f ../../logs/access_log
            192.168.213.1 - - "2022-06-18 23:00:52" "GET /favicon.ico HTTP/1.1" 404 196
            192.168.213.122 - - "2022-06-18 23:00:56" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:00:59" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:00:59" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:01:00" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:01:00" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:01:01" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:01:01" "GET /blog HTTP/1.1" 301 236
            192.168.213.122 - - "2022-06-18 23:01:07" "GET /blog/ HTTP/1.1" 200 384
            

基于用户的访问控制:AuthType

认证质询

  • WWW-Authenticate,响应码为401,拒绝客户端请求,并说明要求客户端需要提供账号和密码

认证

  • Authorization,客户端用户填入账号和密码后再次发送请求报文;认证通过时,则服务器发送响应的资源

认证方式有两种

  • basic:明文(可以通过抓包获取到Authorization标签内的验证信息,即为用户名密码)
  • digest:消息摘要认证,兼容性差

安全域

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

虚拟账号

  • 仅用于访问某服务时用到的认证标识

存储

  • 文本文件,SQL数据库,ldap目录存储,nis等

基于用户账号进行认证

  • 定义安全域

    echo -e \<Directory \/var\/www\/html\/Test>"\n"\
    #定义认证方式AuthType Basic "\n"\
    #定义弹窗提示AuthName \"Input User\/PassWD\""\n"\
    #定义用户文件存放路径AuthUserFile \"\/var\/www\/html\/.htpasswd\""\n"\
    #定义允许那些用户访问Require valid-user"\n"\
    \<\/Directory\> >>  Test.conf[root@xiangdeming extra00:10]#cat Test.conf
    #Listen 8080
    ServerTokens Prod
    ServerAdmin root@xiangdeming.com
    ServerSignature off
    KeepAlive On
    KeepAliveTimeout 15
    <Directory /var/www/html>AllowOverride all<RequireALL>Require all granted Require not ip 192.168.213.123</RequireALL>
    </Directory>
    alias /blog /var/www/html/<Directory /var/www/html/Test>AuthType BasicAuthName "Input User/PassWD"AuthUserFile "/var/www/html/.htpasswd"Require valid-user #在希望某单一用户访问时,将valid-user改为单一的用户名即可;
    </Directory>
    
  • 创建登录用户:使用htpasswd命令完成

    • 常用选项:

      • -c 自动创建文件,仅应该在文件不存在时使用
      • -b 非交互方式创建用户,命令后面可以接密码
      • -p 明文密码
      • -d CRYPT格式加密,默认
      • -m md5格式加密
      • -s sha格式加密
      • -D 删除指定用户
    #创建用户文件,并创建用户Test_user指定密码为“redhat”,若文件已存在时不要带-c参数,不然会覆盖掉原有文件
    [root@xiangdeming extra23:50]#htpasswd -cb /var/www/html/.htpasswd Test_user  "redhat"
    Adding password for user Test_user
    [root@xiangdeming extra23:50]#cat /var/www/html/.htpasswd
    Test_user:$apr1$P71vrJ1d$yTdDMrYBMDGGpyzcE0ceF/
    #验证:
    [root@web-0aadc460 logs16:14]$curl http://192.168.213.100/blog/Test
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>401 Unauthorized</title>
    </head><body>
    <h1>Unauthorized</h1>
    <p>This server could not verify that you
    are authorized to access the document
    requested.  Either you supplied the wrong
    credentials (e.g., bad password), or your
    browser doesn't understand how to supply
    the credentials required.</p>
    </body></html>
    [root@web-0aadc460 logs16:21]$curl http://Test_user:redhat@192.168.213.100/blog/Test/
    www.baidu.com
    

基于组账号进行认证

  • 依赖于用户账号,只是将授权的用户进行分组,授权时对组授权即可,应对与多用户场景

  • 定义安全域

    <Directory /var/www/html/Test>AuthType BasicAuthName "Input User/PassWD"AuthUserFile "/var/www/html/.htpasswd"AuthGroupFile "/var/www/html/.htgroups" #组文件
    #   Require valid-userRequire group webusers #这里写的是组
    </Directory>
    
    #创建用户(请参考基于用户的访问控制)
    [root@xiangdeming extra22:41]#htpasswd -b /var/www/html/.htpasswd Test_user_1  "redhat"
    Adding password for user Test_user_1
    [root@xiangdeming extra22:45]#cat /var/www/html/.htpasswd
    Test_user:$apr1$P71vrJ1d$yTdDMrYBMDGGpyzcE0ceF/
    Test_user_1:$apr1$j8livwoD$RKm1Y15au.B0NWuT26L8w/
    #创建组文件
    tee /var/www/html/.htgroups <<EOF
    webusers: Test_use Test_user_1
    EOF
    [root@xiangdeming extra22:46]#cat /var/www/html/.htgroups
    webusers: Test_user Test_user_1
    #语法检查
    httpd -t
    #重启服务
    systemctl restart httpd
    #尝试访问
    [root@web-0aadc460 ~22:54]$curl http://Test_user:redhat@192.168.213.100/blog/Test/
    www.baidu.com
    [root@web-0aadc460 ~22:56]$curl http://Test_user_1:redhat@192.168.213.100/blog/Test/
    www.baidu.com
    

Status状态页面

httpd 提供了状态页,可以用来观察httpd的运行(负载)情况。此功能需要加载mod_status.so模块才能实现

LoadModule status_module modules/mod_status.so
<Location "/status">
SetHandler server-status
</Location>
ExtendedStatus On #显示扩展信息,httpd 2.3.6以后版默认为On
#配置过程:
#在额外配置文件尾部添加(也可以直接添加在主配置文件中)
<Location "/status">#访问页面路径SetHandler server-status
</Location>
ExtendedStatus On#是否显示扩展信息
#重启服务
systemctl restart httpd
#尝试访问
[root@web-0aadc460 ~23:06]$curl http://192.168.213.100/status
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html><head>
<title>Apache Status</title>
</head><body>
<h1>Apache Server Status for 192.168.213.100 (via 192.168.213.100)</h1><dl><dt>Server Version: Apache/2.4.54 (Unix)</dt>
<dt>Server MPM: event</dt>
<dt>Server Built: Jun 15 2022 22:37:15
</dt></dl><hr /><dl>
<dt>Current Time: Monday, 20-Jun-2022 23:07:59 CST</dt>
<dt>Restart Time: Monday, 20-Jun-2022 23:07:27 CST</dt>
<dt>Parent Server Config. Generation: 1</dt>
<dt>Parent Server MPM Generation: 0</dt>
<dt>Server uptime:  31 seconds</dt>
<dt>Server load: 0.00 0.01 0.01</dt>
<dt>Total accesses: 3 - Total Traffic: 4 kB - Total Duration: 1</dt>
<dt>CPU Usage: u0 s0 cu0 cs0</dt>
<dt>.0968 requests/sec - 132 B/second - 1365 B/request - .333333 ms/request</dt>
<dt>1 requests currently being processed, 74 idle workers</dt>
</dl><table rules="all" cellpadding="1%">
<tr><th rowspan="2">Slot</th><th rowspan="2">PID</th><th rowspan="2">Stopping</th><th colspan="2">Connections</th>
<th colspan="2">Threads</th><th colspan="3">Async connections</th></tr>
<tr><th>total</th><th>accepting</th><th>busy</th><th>idle</th><th>writing</th><th>keep-alive</th><th>closing</th></tr>
<tr><td>0</td><td>3283</td><td>no</td><td>0</td><td>yes</td><td>1</td><td>24</td><td>0</td><td>0</td><td>0</td></tr>
<tr><td>1</td><td>3284</td><td>no</td><td>0</td><td>yes</td><td>0</td><td>25</td><td>0</td><td>0</td><td>0</td></tr>
<tr><td>2</td><td>3285</td><td>no</td><td>0</td><td>yes</td><td>0</td><td>25</td><td>0</td><td>0</td><td>0</td></tr>
<tr><td>Sum</td><td>3</td><td>0</td><td>0</td><td>&nbsp;</td><td>1</td><td>74</td><td>0</td><td>0</td><td>0</td></tr>
</table>
<pre>W_______________________________________________________________
___________.....................................................
................................................................
................................................................
................................................................
................................................................
................</pre>
<p>Scoreboard Key:<br />
"<b><code>_</code></b>" Waiting for Connection,
"<b><code>S</code></b>" Starting up,
"<b><code>R</code></b>" Reading Request,<br />
"<b><code>W</code></b>" Sending Reply,
"<b><code>K</code></b>" Keepalive (read),
"<b><code>D</code></b>" DNS Lookup,<br />
"<b><code>C</code></b>" Closing connection,
"<b><code>L</code></b>" Logging,
"<b><code>G</code></b>" Gracefully finishing,<br />
"<b><code>I</code></b>" Idle cleanup of worker,
"<b><code>.</code></b>" Open slot with no current process<br />
</p><table border="0"><tr><th>Srv</th><th>PID</th><th>Acc</th><th>M</th><th>CPU
</th><th>SS</th><th>Req</th><th>Dur</th><th>Conn</th><th>Child</th><th>Slot</th><th>Client</th><th>Protocol</th><th>VHost</th><th>Request</th></tr><tr><td><b>0-0</b></td><td>3283</td><td>1/0/0</td><td><b>W</b>
</td><td>0.00</td><td>0</td><td>0</td><td>0</td><td>0.0</td><td>0.00</td><td>0.00
</td><td>192.168.213.122</td><td>http/1.1</td><td nowrap>www.Deming.org:80</td><td nowrap>GET /status HTTP/1.1</td></tr><tr><td><b>2-0</b></td><td>3285</td><td>0/1/1</td><td>_
</td><td>0.00</td><td>18</td><td>0</td><td>0</td><td>0.0</td><td>0.00</td><td>0.00
</td><td>192.168.213.1</td><td>http/1.1</td><td nowrap>www.Deming.org:80</td><td nowrap>GET / HTTP/1.1</td></tr><tr><td><b>2-0</b></td><td>3285</td><td>0/1/1</td><td>_
</td><td>0.00</td><td>18</td><td>0</td><td>0</td><td>0.0</td><td>0.00</td><td>0.00
</td><td>192.168.213.1</td><td>http/1.1</td><td nowrap>www.Deming.org:80</td><td nowrap>GET /favicon.ico HTTP/1.1</td></tr><tr><td><b>2-0</b></td><td>3285</td><td>0/1/1</td><td>_
</td><td>0.00</td><td>12</td><td>0</td><td>0</td><td>0.0</td><td>0.00</td><td>0.00
</td><td>192.168.213.1</td><td>http/1.1</td><td nowrap>www.Deming.org:80</td><td nowrap>GET /status HTTP/1.1</td></tr></table><hr /> <table><tr><th>Srv</th><td>Child Server number - generation</td></tr><tr><th>PID</th><td>OS process ID</td></tr><tr><th>Acc</th><td>Number of accesses this connection / this child / this slot</td></tr><tr><th>M</th><td>Mode of operation</td></tr>
<tr><th>CPU</th><td>CPU usage, number of seconds</td></tr>
<tr><th>SS</th><td>Seconds since beginning of most recent request</td></tr><tr><th>Req</th><td>Milliseconds required to process most recent request</td></tr><tr><th>Dur</th><td>Sum of milliseconds required to process all requests</td></tr><tr><th>Conn</th><td>Kilobytes transferred this connection</td></tr><tr><th>Child</th><td>Megabytes transferred this child</td></tr><tr><th>Slot</th><td>Total megabytes transferred this slot</td></tr></table>
</body></html>
  • 添加状态页面验证

    • 注意:IP控制和用户控制只能生效一个,不能一起生效;

    • 用户控制优先级更高;

      #创建用户授权文件
      [root@xiangdeming conf23:16]#htpasswd -cb .htpasswd Status_user redhat
      Adding password for user Status_user
      #修改额外配置文件配置,添加用户认证部分
      <Location "/status">SetHandler server-statusAuthType BasicAuthName "Input User/PassWD"AuthUserFile "/apps/httpd/conf/.htpasswd"Require valid-user
      </Location>
      ExtendedStatus On
      #重启服务
      systemctl restart httpd.service
      #尝试访问
      [root@web-0aadc460 ~23:06]$curl http://192.168.213.100/status
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
      <html><head>
      <title>401 Unauthorized</title>
      </head><body>
      <h1>Unauthorized</h1>
      <p>This server could not verify that you
      are authorized to access the document
      requested.  Either you supplied the wrong
      credentials (e.g., bad password), or your
      browser doesn't understand how to supply
      the credentials required.</p>
      </body></html>
      [root@web-0aadc460 ~23:16]$curl http://Status_user:redhat@192.168.213.100/status
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
      <html><head>
      <title>Apache Status</title>
      </head><body>
      <h1>Apache Server Status for 192.168.213.100 (via 192.168.213.100)</h1><dl><dt>Server Version: Apache/2.4.54 (Unix)</dt>
      <dt>Server MPM: event</dt>
      <dt>Server Built: Jun 15 2022 22:37:15
      </dt></dl><hr /><dl>
      <dt>Current Time: Monday, 20-Jun-2022 23:19:06 CST</dt>
      <dt>Restart Time: Monday, 20-Jun-2022 23:18:34 CST</dt>
      <dt>Parent Server Config. Generation: 1</dt>
      ...
      
      #IP控制
      <Location "/status"><RequireALL>Require all  deniedRequire ip 192.168.213.122</RequireALL>SetHandler server-status
      </Location>
      ExtendedStatus On
      

多虚拟主机

httpd 支持在一台物理主机上实现多个网站,即多虚拟主机
网站的唯一标识

  • IP相同,但端口不同
  • IP不同,但端口均为默认端口
  • FQDN不同, IP和端口都相同

多虚拟主机有三种实现方案

  • 基于ip:为每个虚拟主机准备至少一个ip地址
  • 基于port:为每个虚拟主机使用至少一个独立的port
  • 基于FQDN:为每个虚拟主机使用至少一个FQDN,请求报文中首部 Host: www.example.com

注意:httpd 2.4版本中,基于FQDN的虚拟主机不再需要NameVirutalHost指令

虚拟主机的配置方法:

  • #方法一:基于IP(不推荐)
#修改配置文件,增加虚拟主机配置
<VirtualHost 192.168.213.193:80>DocumentRoot "/var/www/Test1"<Directory /var/www/Test1>Require all granted</Directory>
</VirtualHost><VirtualHost 192.168.213.194:80>DocumentRoot "/var/www/Test2"<Directory /var/www/Test2>Require all granted</Directory>
</VirtualHost>
<VirtualHost 192.168.213.195:80>DocumentRoot "/var/www/Test3"<Directory /var/www/Test3>Require all granted</Directory>
</VirtualHost>
</VirtualHost>
#环境准备
for((i=1;i<=3;i++));domkdir /var/www/Test"$i"echo "This is var/www/Test$i" >> /var/www/Test"$i"/index.html#这里是临时配置,可以选择用nmcli或者手动创建文件的方式实现永久IPip addr add 192.168.213.19"$((i+2))"/24 dev ens33  label ens33:"$i"
done
#语法检查
httpd -t
#重启服务
systemctl restart httpd.service
#尝试访问
[root@web-0aadc460 ~00:18]$curl 192.168.213.193
This is var/www/Test1
[root@web-0aadc460 ~00:18]$curl 192.168.213.194
This is var/www/Test2
[root@web-0aadc460 ~00:18]$curl 192.168.213.195
This is var/www/Test3
  • 方法二:基于端口
#修改配置文件,增加虚拟主机配置
listen 81
<VirtualHost *:81>DocumentRoot "/var/www/Test1"<Directory /var/www/Test1>Require all granted</Directory>
</VirtualHost>listen 82
<VirtualHost *:82>DocumentRoot "/var/www/Test2"<Directory /var/www/Test2>Require all granted</Directory>
</VirtualHost>listen 83
<VirtualHost *:83>DocumentRoot "/var/www/Test3"<Directory /var/www/Test3>Require all granted</Directory>
</VirtualHost>
#环境准备
for((i=1;i<=3;i++));domkdir /var/www/Test"$i"echo "This is var/www/Test$i" >> /var/www/Test"$i"/index.html
done
#语法检查
httpd -t
#重启服务
systemctl restart httpd.service
#尝试访问
[root@web-0aadc460 ~00:31]$curl 192.168.213.100:81
This is var/www/Test1
[root@web-0aadc460 ~00:31]$curl 192.168.213.100:82
This is var/www/Test2
[root@web-0aadc460 ~00:32]$curl 192.168.213.100:83
This is var/www/Test3
  • 基于FQNAME的方式
#修改hosts文件,或者修改DNS的解析文件
echo -e 192.168.213.100 www.Test1.com www.Test2.com www.Test3.com >> /etc/hosts
#修改额外配置文件
<VirtualHost *:80>servername www.Test1.comDocumentRoot "/var/www/Test1"<Directory /var/www/Test1>Require all granted</Directory>
</VirtualHost><VirtualHost *:80>servername www.Test2.comDocumentRoot "/var/www/Test2"<Directory /var/www/Test2>Require all granted</Directory>
</VirtualHost><VirtualHost *:80>servername www.Test3.comDocumentRoot "/var/www/Test3"<Directory /var/www/Test3>Require all granted</Directory>
</VirtualHost>
#环境准备
for((i=1;i<=3;i++));domkdir /var/www/Test"$i"echo "This is var/www/Test$i" >> /var/www/Test"$i"/index.html
done
#尝试访问
[root@web-0aadc460 ~00:44]$echo -e 192.168.213.100 www.Test1.com www.Test2.com www.Test3.com >> /etc/hosts
[root@web-0aadc460 ~00:45]$curl www.Test1.com
This is var/www/Test1
[root@web-0aadc460 ~00:45]$curl www.Test2.com
This is var/www/Test2
[root@web-0aadc460 ~00:45]$curl www.Test3.com
This is var/www/Test3

网页压缩

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

LoadModule deflate_module modules/mod_deflate.so SetOutputFilter

适用场景

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

  2. 压缩适于压缩的资源,例如文本文件

资源类型查看

  • /etc/mime.types

常用压缩指令说明

#可选项
SetOutputFilter DEFLATE
# 指定对哪种MIME类型进行压缩,必须指定项
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/css
#压缩级别 (Highest 9 - Lowest 1)
DeflateCompressionLevel 9
#排除特定旧版本的浏览器,不支持压缩
#Netscape 4.x 只压缩text/html
BrowserMatch ^Mozilla/4 gzip-only-text/html
#Netscape 4.06-08 三个版本 不压缩
BrowserMatch ^Mozilla/4\.0[678] no-gzip
#Internet Explorer标识本身为"Mozilla / 4”,但实际上是能够处理请求的压缩。如果用户代理首部匹
配字符串"MSIE”("B”为单词边界”),就关闭之前定义的限制
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

压缩普通文件

#修改主配置文件(编译安装适用)
[root@xiangdeming conf01:49]#grep -i "deflate_module" httpd.conf
#LoadModule deflate_module modules/mod_deflate.so
[root@xiangdeming conf01:50]#sed -ri "s/^#(LoadModule deflate_module.*)/\1/" httpd.conf
[root@xiangdeming conf01:50]#grep -in "deflate_module" httpd.conf
108:LoadModule deflate_module modules/mod_deflate.so
#修改配置文件
#-------------虚拟主机配置----------------#
listen 81
<VirtualHost *:81>servername www.Test1.comDocumentRoot "/var/www/Test1"
<Directory /var/www/Test1>Require all grantedOptions indexes
</Directory>
#---------------------压缩-------------------#
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
#-------------------压缩级别-----------------#
DeflateCompressionLevel 9
</VirtualHost>
#重启服务
[root@xiangdeming extra01:52]#!sys
systemctl restart httpd.service
#查看日志,可以发现访问大小为132K
[root@xiangdeming extra01:56]#tail -f /apps/httpd/logs/access_log
192.168.213.1 - - "2022-06-21 01:56:06" "GET / HTTP/1.1" 200 180
192.168.213.1 - - "2022-06-21 01:56:40" "GET / HTTP/1.1" 200 180
192.168.213.1 - - "2022-06-21 01:56:40" "GET /favicon.ico HTTP/1.1" 404 196
192.168.213.1 - - "2022-06-21 01:57:05" "GET / HTTP/1.1" 200 45
192.168.213.1 - - "2022-06-21 01:57:05" "GET /favicon.ico HTTP/1.1" 404 196
192.168.213.1 - - "2022-06-21 01:57:09" "GET / HTTP/1.1" 200 180
192.168.213.1 - - "2022-06-21 01:57:09" "GET /favicon.ico HTTP/1.1" 404 196
192.168.213.1 - - "2022-06-21 01:57:13" "GET /1.txt HTTP/1.1" 200 135460
#对比原文件(大小为655K)
[root@xiangdeming extra02:00]#ll -h /var/www/Test1/1.txt
-rw-r--r-- 1 root root 655K 6月  21 01:32 /var/www/Test1/1.txt
#也可以使用curl命令访问查看详细信息
[root@web-0aadc460 ~01:47]$curl -v --compressed 192.168.213.100:81/1.txt |head -20
* About to connect() to 192.168.213.100 port 81 (#0)
*   Trying 192.168.213.100...% Total    % Received % Xferd  Average Speed   Time    Time     Time  CurrentDload  Upload   Total   Spent    Left  Speed0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to 192.168.213.100 (192.168.213.100) port 81 (#0)
> GET /1.txt HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.213.100:81
> Accept: */*
> Accept-Encoding: deflate, gzip
>
< HTTP/1.1 200 OK
< Date: Mon, 20 Jun 2022 18:05:18 GMT
< Server: Apache
< Last-Modified: Mon, 20 Jun 2022 17:32:45 GMT
< ETag: "a3a55-5e1e47dfa90a9-gzip"
< Accept-Ranges: bytes
< Vary: Accept-Encoding
< Content-Encoding: gzip
< Transfer-Encoding: chunked
< Content-Type: text/plain
  • 压缩开启前

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fpFF7QN8-1655833825372)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220621015523072.png)]

  • 压缩开启后

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gHskSr4G-1655833825374)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220621015757910.png)]

实现网页验证与加密-HTTPS

Https说明:

  • http over ssl ,实现验证和加密功能

HTTPS简化的通信过程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FucMRHsC-1655833825374)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220621021023898.png)]

  1. 客户端发送可供选择的加密方式,并向服务器请求证书

  2. 服务器端发送证书以及选定的加密方式给客户端

  3. 客户端取得证书并进行证书验证,如果信任给其发证书的CA
    (a) 验证证书来源的合法性;用CA的公钥解密证书上数字签名
    (b) 验证证书的内容的合法性:完整性验证
    © 检查证书的有效期限
    (d) 检查证书是否被吊销
    (e) 证书中拥有者的名字,与访问的目标主机要一致

  4. 客户端生成临时会话密钥(对称密钥),并使用服务器端的公钥加密此数据发送给服务器,完成密
    钥交换

  5. 服务用此密钥加密用户请求的资源,响应给客户端

    注意:SSL是基于IP地址实现,单IP的httpd主机,仅可以使用一个https虚拟主机

自签名证书创建

#安装rpm包mod_ssl
yum -y install mod_ssl
#修改ssl加密设置
sed -ri "s/(.*-aes128.*@)$/#\1/" Makefile
sed -rn "/^#.*-aes128.*@$/a\  \/usr/bin/openssl genrsa \$\(KEYLEN\) \> \$@" Makefile
[root@xiangdeming certs22:17]#grep -A3 "^%.key" Makefile
%.key:umask 77 ; \
#   /usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@/usr/bin/openssl genrsa $(KEYLEN) > $@
#创建证书
[root@xiangdeming certs22:19]#make httpd.crt
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key httpd.key -x509 -days 365 -out httpd.crt
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) []:SHENZHENG
Locality Name (eg, city) [Default City]:shenzheng
Organization Name (eg, company) [Default Company Ltd]:Xiangdeming
Organizational Unit Name (eg, section) []:it
Common Name (eg, your name or your server's hostname) []:www.xiangdeming.org
Email Address []:
#替换ssl.conf配置文件证书路径(编译安装不要做这一步)
sed -ri "s/^(SSL.*File) .*\.crt/\1 \/etc\/pki\/tls\/certs\/httpd.crt/" /etc/httpd/conf.d/ssl.conf
sed -ri "s/^(SSL.*File) .*\.key/\1 \/etc\/pki\/tls\/certs\/httpd.key/" /etc/httpd/conf.d/ssl.conf
[root@xiangdeming certs22:28]#grep -E "^SSL.*File" /etc/httpd/conf.d/ssl.conf
SSLCertificateFile /etc/pki/tls/certs/httpd.crt
SSLCertificateKeyFile /etc/pki/tls/certs/httpd.key
#重启服务即可
#编译安装实现自签名
#修改httpd的主配置文件(编译安装步骤)
httpd -M | grep ssl
sed -ri "s/^#(LoadModule ssl_module.*)/\1/" httpd.con
sed -ri "s/^#(LoadModule socache_shmcb_module.*)/\1/" httpd.conf
sed -ri "s/#(Include conf\/extra\/httpd-ssl.conf)/\1/" httpd.conf
mkdir /apps/httpd/conf/ssl
chown -R apache.apache /apps/httpd/conf.d/ssl/
cp  /etc/pki/tls/certs/httpd.* .
#修改主配置文件
sed -ri "s/^(SSL.*File) .*\.crt/\1 \/apps\/httpd\/conf\/ssl\/httpd.crt/ /apps/httpd/conf/extra/httpd-ssl.conf
sed -ri "s/^(SSL.*File) .*\.key/\1 \/apps\/httpd\/conf\/ssl\/httpd.key/ /apps/httpd/conf/extra/httpd-ssl.conf
#卸载httpd的rpm包(若有)
#重新写环境变量
echo 'PATH=/apps/httpd/bin:$PATH' > /etc/profile.d/httpd.sh
. /etc/profile.d/httpd.sh
#重新生成unit文件
[root@xiangdeming conf23:07]#cat /usr/lib/systemd/system/httpd.service
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)
[Service]
Type=forking
#EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/apps/httpd/bin/apachectl start
#ExecStart=/apps/httpd/bin/httpd $OPTIONS -k start
ExecReload=/apps/httpd/bin/apachectl graceful
#ExecReload=/apps/httpd/bin/httpd $OPTIONS -k graceful
ExecStop=/apps/httpd/bin/apachectl stop
KillSignal=SIGCONT
PrivateTmp=true
[Install]
WantedBy=multi-user.target
#重启服务
systemctl restart httpd
#验证
curl -k https://www.xiangdeming.org/blog

URL重定向:Redirect与RewriteEngine

URL重定向,即将httpd 请求的URL转发至另一个的URL

重定向指令格式

Redirect [status] URL-path URL

status状态

  1. permanent: 返回永久重定向状态码 301,此重定向信息在硬盘上缓存
  2. temp:返回临时重定向状态码302. 此为默认值,不缓存

HTTPD功能实现脚本(编译安装)

#-----------------------------------------额外功能------------------------------------------#
#实现指定服务器名称
function Servername()
{httpd -t |grep -i "AH005578" && sed -ri "s/^#(Server.*)/\1/" /apps/httpd/conf/httpd.confsed -ri "/^#ServerName/a ServerName www.Deming.org:8001" /apps/httpd/conf/httpd.conf
}#生成额外配置文件,并隐藏服务器版本信息与关闭错误信息
function Extra_conf()
{grep -Ei "^IncludeOptiona" && echo "IncludeOptional conf/extra/Test.conf" >> /apps/conf/httpd.conf[ ! -f /apps/httpd/extra/Test.conf ] && touch /apps/httpd/conf/extra/Test.confcd /apps/httpd/conf/extra/Test.con || exit#隐藏网页版本grep -i "ServerTokens" /apps/httpd/conf/httpd.conf && echo "ServerTokens Prod" >> Test.conf#关闭报错的信息泄露echo -e ServerAdmin root@xiangdeming.com"\n"ServerSignature off >> Test.conf
}#持久链接开启与关闭
function Permanent_link()
{read -r -p "是否开启持久链接(yes/no):" Options_1case "$Options_1" inyes)#开启持久链接,并设置为15秒cd /apps/httpd/conf/extra/ || exit 1echo "默认持续连接为15秒,并发为500"if [[ ! $(grep "KeepAlive" Test.conf|awk 'NR==1{print $2}') =~ [On|on|ON] ]];thengrep "KeepAlive" Test.conf &&\{sed -ri "s/(KeepAlive).*/\1 On" Test.confsed -ri "s/(KeepAliveTimeout).*/\1 15/" Test.confsed -ri "s/(MaxKeepAliveRequests).*/\1 500" Test.conf} ||\echo -e KeepAlive On"\n"KeepAliveTimeout 15"\n"MaxKeepAliveRequests 500  >> Test.conf    fi;;no)grep "KeepAlive" Test.conf &&\{sed -ri "s/(KeepAlive).*/\1 Off" Test.conf  &>/dev/nullsed -ri "s/(KeepAliveTimeout).*/#\1/" Test.conf &>/dev/nullsed -ri "s/(MaxKeepAliveRequests).*/#\1" Test.conf &>/dev/null} ||\echo -e KeepAlive Off >> Test.conf;;*)echo "输出错误,请输入yes/no";;esac
}#修改httpd-MPM工作模式:prefork,worker,event
function Change_MPM()
{mod=$(httpd -M |grep -i mpm|awk '{print $1}')cd /apps/httpd/conf/ || exitread -r -p "当前运行模式为$mod,请输入需要修改的模式(prefork、worker、event),不修改则输入No:" Options_2case $Options_2 inprefork)if [[ ! $mod =~ mpm_prefork_module ]];thensed -ri "/^LoadModule $mod.*/#\1" httpd.confsed -ri "/^#LoadModule mpm_prefork_module.*/s/#//" httpd.confsed -ri "s/.*StartServers.*/\1 100/" extra/Test.conf 2>/dev/null || echo "StartServers 100" >> extra/Test.confsed -ri "s/.*MinSpareServers.*/\1 50/" extra/Test.conf 2>/dev/null || echo "MinSpareServers 50" >> extra/Test.confsed -ri "s/.*MaxSpareServers.*/\1 80/" extra/Test.conf 2>/dev/null || echo "MaxSpareServers 80" >> extra/Test.confsed -ri "s/.*ServerLimit.*/\1 2560/" extra/Test.conf 2>/dev/null || echo "ServerLimit 2560" >> extra/Test.confsed -ri "s/.*MaxRequestWorkers.*/\1 2560/" extra/Test.conf 2>/dev/null || echo "MaxRequestWorkers 2560" >> extra/Test.confsed -ri "s/.*MaxConnectionsPerChild.*/\1 4000/" extra/Test.conf 2>/dev/null || echo "MaxConnectionsPerChild 4000" >> extra/Test.confsed -ri "s/.*MaxRequestsPerChild.*/\1 4000/" extra/Test.conf 2>/dev/null || echo "MaxRequestsPerChild 4000" >> extra/Test.confsystecmctl restart httpd && action "修改完成"elseaction "修改完成"fi;;[worker])if [[ ! $mod =~ mpm_worker_module ]];thensed -ri "/^LoadModule $mod.*/#\1" httpd.confsed -ri "/^#LoadModule mpm_worker_module.*/s/#//" httpd.confsed -ri "s/.*ServerLimit.*/\1 16/" extra/Test.conf 2>/dev/null || echo "ServerLimit 16" >> extra/Test.confsed -ri "s/.*StartServers.*/\1 10/" extra/Test.conf 2>/dev/null || echo "StartServers 10" >> extra/Test.confsed -ri "s/.*MaxRequestWorkers.*/\1 150/" extra/Test.conf 2>/dev/null || echo "MaxRequestWorkers 150" >> extra/Test.confsed -ri "s/.*MinSpareThreads.*/\1 25/" extra/Test.conf 2>/dev/null || echo "MinSpareThreads 25" >> extra/Test.confsed -ri "s/.*MaxSpareThreads.*/\1 75/" extra/Test.conf 2>/dev/null || echo "MaxSpareThreads 75" >> extra/Test.confsed -ri "s/.*ThreadsPerChild.*/\1 25/" extra/Test.conf 2>/dev/null || echo "ThreadsPerChild 25" >> extra/Test.confsystecmctl restart httpd && action "修改完成"elseaction "修改完成"fi;;event)if [[ ! $mod =~ mpm_event_module ]];thensed -ri "/^LoadModule $mod.*/#\1" httpd.confsed -ri "/^#LoadModule mpm_event_module.*/s/#//" httpd.confsed -ri "s/.*ServerLimit.*/\1 16/" extra/Test.conf 2>/dev/null || echo "ServerLimit 16" >> extra/Test.confsed -ri "s/.*StartServers.*/\1 10/" extra/Test.conf 2>/dev/null || echo "StartServers 10" >> extra/Test.confsed -ri "s/.*MaxRequestWorkers.*/\1 150/" extra/Test.conf 2>/dev/null || echo "MaxRequestWorkers 150" >> extra/Test.confsed -ri "s/.*MinSpareThreads.*/\1 25/" extra/Test.conf 2>/dev/null || echo "MinSpareThreads 25" >> extra/Test.confsed -ri "s/.*MaxSpareThreads.*/\1 75/" extra/Test.conf 2>/dev/null || echo "MaxSpareThreads 75" >> extra/Test.confsed -ri "s/.*ThreadsPerChild.*/\1 25/" extra/Test.conf 2>/dev/null || echo "ThreadsPerChild 25" >> extra/Test.confsystecmctl restart httpd && action "修改完成"elseaction "修改完成"fi;;No)exit;;*)echo "请输入需要修改的模式(prefork、worker、event),不修改则输入No";;esac
}#创建别名
function Create_Alias()
{local source_pathlocal alias_pathread -r -p "请输入源目录路径和创建的别名路径" source_path alias_path[ ! -e "$source_path" ] && [[ "$source_path" =~ ^/.*/$ ]] && [ -d "$source_path" ] || echo "源目录不存在"[ ! -e "$alias_path"  ] && [[ "$alias_path" =~ ^/.*/$ ]] || echo "别名为空值或路径违法"[ -d "$alias_path" ] || mkdir "$alias_path"cd /apps/httpd/conf/extra || exit#配置源目录(默认允许所有访问)echo -e "<Directory \"${source_path}\">" "\n"\  Require all granted "\n"'</Directory\>' >> Test.conf#配置别名sed -ri "s/^([Aa]lias).*/\1 ${alias_path} ${source_path}/" ||echo "alias ${alias_path} ${source_path}" >> Test.conf#重启服务systemctl restart httpd && action "alias配置完成"
}

HTTP协议和web服务技术---Apche配置相关推荐

  1. HTTP协议和web工作原理

    HTTP协议和web工作原理 http://blog.csdn.net/kjfcpua/archive/2009/12/04/4932597.aspx 本章学完之后能干什么? 要把 知识点学好,那就需 ...

  2. Web服务技术协议:REST与SOAP

    Web服务技术就有SOAP(Simple Object Access Protocol,简单对象访问协议)和REST(Representational State Transfer,表示性状态转移) ...

  3. Web服务技术与应用

    一些基本的Web理论知识适当结合了一些实例. 主要涵盖内容有:HTML+CSS+JSP+JDBC+AJAX+XML+WebService+EJB+Servlet. Web 概述 Web是Interne ...

  4. 计算机网络——HTTP协议和Web

    文章目录 一.基本知识 二.非持续连接与持续链接 1.采用持续连接的HTTP 2.采用非持续连接的HTTP 三.HTTP报文格式 1.请求报文 2.应答报文 五.cookie 六.Web缓存 1.基本 ...

  5. 客户端/服务器程序_了解客户端/服务器协议和Web应用程序

    客户端/服务器程序 Introduction 介绍 HyperText Transfer Protocol or "HTTP" is the underpinning of int ...

  6. web服务软件 html5,配置WEB服务器(apache,nginx),支持 html5 video(ogv, webm.etc)播放...

    nginx默认丢失了 html5视频的媒体类型,比如Ogg\Ogv\WebM等,要支持这些媒体类型, 必须自己添加相应媒体类型到 nginx/conf/mime.types (Windows版本)文件 ...

  7. 2、nginx常用配置----作为web服务端

    目录 环境及目的 nginx配置文件特点和结构 1 特性 2 主配置文件结构 常用全局配置 1 main段 2 events段 web服务相关配置 1 server_namerootlisten 11 ...

  8. [GIS原理] 资源共享-SIG|服务篇(服务型GIS、SOA架构、Web Services技术、GIS服务、地理空间服务聚合、地理空间服务网络)

    文章目录 资源共享 空间信息栅格SIG 服务篇 资源共享 空间信息栅格SIG 说明 信息格网 [what]Information Grid ①利用现有的网络基础设施.协议规范.Web和数据库技术,为用 ...

  9. jboss4 java_JBoss核心Java Web服务

    jboss4 java 这篇博客文章涉及Web服务. 好吧,更确切地说,它处理JBoss上的"普通" java Web服务. 这意味着我们将创建一个没有任何其他框架(例如CXF,A ...

  10. JBoss核心Java Web服务

    这篇博客文章涉及Web服务. 好吧,更确切地说,它处理JBoss上的"普通" java Web服务. 这意味着我们将创建一个没有任何其他框架(如CXF,Axis等)的Web服务. ...

最新文章

  1. 网络工程师_记录的一些真题_2007下半年上午
  2. 小松卡特彼勒无人驾驶_运输量突破20亿吨,卡特彼勒无人驾驶矿卡迎里程碑时刻...
  3. 多线程题目 2019.06.02 晚
  4. python基础——if语句/条件控制
  5. 移动IM开发那些事:技术选型和常见问题
  6. 开始使用ASP.NET核心运行状况检查
  7. HDU2156 分数矩阵【数学计算+水题】
  8. ROS+Gazebo仿真差速小车并实现控制
  9. POJ 1149 PIGS(最大流)dinic模板注释
  10. Atitit. Java script 多重多重catch语句的实现and Javascript js 异常机制
  11. 汉中市驾驶员理论模拟考试题
  12. 关于用户登录的记住密码实现思路(考虑到安全问题)
  13. 遥感图像裁剪后在ENVI里显示为黑色解决办法
  14. [C++][题解]切蛋糕
  15. 校内校园网络技术标书(三少原创)
  16. PostGIS搭建、空间数据库创建
  17. uni-app - 设置最外层容器高度为100%
  18. MapBoxGL.JS 画圆 (半径以米或千米为单位) 实现跟随地图缩放而缩放
  19. 【C语言】深度理解 负数取余 取模
  20. NIO、AIO概述总结

热门文章

  1. 利用Python破解隔壁老王家的WiFi密码,学习到了!
  2. 深圳市自助图书馆详细分布地址
  3. java gbk编码_JAVA中文字符串编码--GBK转UTF-8
  4. 33c3 CTF web WriteUp
  5. 动态设置Button图片大小
  6. python--基于百度aip的语音交互及语音唤醒
  7. 2021年焊工(初级)试题及解析及焊工(初级)实操考试视频
  8. php 读取 eml,php如何读取解析eml文件以及生成网页的示例分享
  9. 对注册表项“HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run”的访问被拒绝。
  10. 手机屏幕密码怎么用计算机解锁,手机屏幕密码忘了怎么解锁