02-一键部署httpd与常见配置
一键部署httpd
- 范例1
#!/bin/bash #Author: #Description: httpd source code install #下载源码包 target_dir=/usr/local/src install_dir=/usr/local/httpd download_url=https://mirror.bit.edu.cn/apache/httpd/httpd-2.4.46.tar.bz2 file_name=${download_url##*/} uncompress_dir=${file_name%.tar*} rpm -q wget || yum install -y wget wget -O $target_dir/$file_name $download_url #安装依赖包 yum install -y gcc make apr-devel apr-util-devel pcre-devel openssl-devel redhat-rpm-config #添加apache用户 id apache &> /dev/null || useradd -r -u 80 -d /var/www -s /sbin/nologin apache #解压源码包 tar xf $target_dir/$file_name -C $target_dir cd $target_dir/$uncompress_dir #编译安装 ./configure --prefix=$install_dir --sysconfdir=/etc/httpd --enable-ssl make -j`lscpu | grep "^CPU(s)" | awk '{print $NF}'` && make install #设置环境变量 echo 'PATH='$install_dir'/bin:$PATH' > /etc/profile.d/httpd.sh source /etc/profile.d/httpd.sh #修改配置文件 sed -ri 's#(User )daemon#\1apache#' /etc/httpd/httpd.conf sed -ri 's#(Group )daemon#\1apache#' /etc/httpd/httpd.conf #启动httpd服务 cat > /lib/systemd/system/httpd.service << 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=/usr/local/httpd/bin/apachectl start ExecReload=/usr/local/httpd/bin/apachectl graceful ExecStop=/usr/local/httpd/bin/apachectl stop KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable httpd.service systemctl start httpd.service #检查firewalld状态 firewall_status=`firewall-cmd --state` if [ $firewall_status = running ];then echo "防火墙已启用,开放端口" firewall-cmd --permanent --add-service=http --add-service=https firewall-cmd --reload fi
范例2:
#!/bin/bash #Author: CPUS=`lscpu |grep "CPU(s)"|awk '{print $2}'|head -1` HTTP_URL="https://mirrors.tuna.tsinghua.edu.cn/apache/httpd/httpd-2.4.46.tar.gz" HTTP_FILE="${HTTP_URL##*/}" APR_URL="https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-1.7.0.tar.gz" APR_FILE="${APR_URL##*/}" APR_UTIL_URL="https://mirrors.tuna.tsinghua.edu.cn/apache/apr/apr-util- 1.6.1.tar.gz" APR_UTIL_FILE="${APR_UTIL_URL##*/}" INSTALL_DIR="/apps/httpd24" install_package(){ grep "Ubuntu" /etc/issue &> /dev/null if [ $? -eq 0 ] ;then apt -y install build-essential libpcre3 libpcre3-dev openssl libssl-dev libexpat1-dev wget fi grep "Kernel" /etc/issue &> /dev/null if [ $? -eq 0 ] ;then yum -y install gcc make pcre-devel openssl-devel expat-devel wget fi wget ${HTTP_URL} && wget ${APR_URL} && wget ${APR_UTIL_URL} } install_http(){ tar xvf ${HTTP_FILE} && tar xvf ${APR_FILE} && tar xvf ${APR_UTIL_FILE} mv ${APR_FILE%.tar*} ${HTTP_FILE%.tar*}/srclib/apr mv ${APR_UTIL_FILE%.tar*} ${HTTP_FILE%.tar*}/srclib/apr-util cd ${HTTP_FILE%.tar*} ./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=event make -j ${CPUS} && make install #环境 echo "${INSTALL_DIR}/bin:$PATH" > /etc/profile.d/http24.sh . /etc/profile.d/http24.sh #创建用户 useradd -s /sbin/nologin -r apache #更改运行用户 sed -Ei "s/daemon/apache/g" ${INSTALL_DIR}/conf/httpd.conf #创建service cat > /lib/systemd/system/httpd.service <<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=\${INSTALL_DIR}/bin/apachectl start ExecReload=\${INSTALL_DIR}/bin/apachectl graceful ExecStop=\${INSTALL_DIR}/bin/apachectl stop KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable --now httpd } main(){ install_package install_http } main
范例3:
#!/bin/bash # #******************************************************************** #Author: #Date: 2022-02-28 #FileName: install_httpd2.4.46.sh #URL: www.neteagles.cn #Description: install_httpd2.4.46 for centos 7/8 & ubuntu 18.04/20.04 #Copyright (C): 2021 All rights reserved #******************************************************************** APR_URL=https://mirrors.tuna.tsinghua.edu.cn/apache/apr/ APR_FILE=apr-1.7.0 TAR=.tar.bz2 APR_UTIL_URL=https://mirrors.tuna.tsinghua.edu.cn/apache/apr/ APR_UTIL_FILE=apr-util-1.6.1 HTTPD_URL=https://mirrors.tuna.tsinghua.edu.cn/apache/httpd/ HTTPD_FILE=httpd-2.4.46 INSTALL_DIR=/apps/httpd24 CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'` MPM=event install_httpd(){ if [ `awk -F'"' '/^ID=/{print $2}' /etc/os-release` == "centos" ] &> /dev/null;then yum -y install gcc make pcre-devel openssl-devel expat-devel wget bzip2 else apt update apt -y install gcc make libapr1-dev libaprutil1-dev libpcre3 libpcre3-dev libssl-dev wget fi cd /usr/local/src wget $APR_URL$APR_FILE$TAR && wget $APR_UTIL_URL$APR_UTIL_FILE$TAR && wget $HTTPD_URL$HTTPD_FILE$TAR tar xf $APR_FILE$TAR && tar xf $APR_UTIL_FILE$TAR && tar xf $HTTPD_FILE$TAR mv $APR_FILE $HTTPD_FILE/srclib/apr mv $APR_UTIL_FILE $HTTPD_FILE/srclib/apr-util cd $HTTPD_FILE ./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=$MPM make -j $CPUS && make install useradd -s /sbin/nologin -r apache sed -i 's/daemon/apache/' $INSTALL_DIR/conf/httpd.conf echo "PATH=$INSTALL_DIR/bin:$PATH" > /etc/profile.d/http24.sh . /etc/profile.d/http24.sh cat > /lib/systemd/system/httpd.service <<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=${INSTALL_DIR}/bin/apachectl start ExecReload=${INSTALL_DIR}/bin/apachectl graceful ExecStop=${INSTALL_DIR}/bin/apachectl stop KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable --now httpd }
install_httpd
- 利用ansible 的playbook 实现批量编译安装部署 httpd-2.4
[root@ansible ansible]#cat install_httpd.yml --- - hosts: websrvs remote_user: root vars: download_dir: /usr/local/src install_dir: /apps/httpd httpd_version: httpd-2.4.46 apr_version: apr-1.7.0 apr_util_version: apr-util-1.6.1 httpd_url: https://mirrors.tuna.tsinghua.edu.cn/apache/httpd apr_url: https://mirrors.tuna.tsinghua.edu.cn/apache/apr tasks: - name: install packages yum: name=gcc,make,pcre-devel,openssl-devel,expat-devel,bzip2 state=installed - name: download httpd file unarchive: src="{{ httpd_url }}/{{ httpd_version }}.tar.bz2" dest={{ download_dir }} owner=root remote_src=yes - name: download apr file unarchive: src="{{ apr_url }}/{{ apr_version }}.tar.bz2" dest={{ download_dir }} owner=root remote_src=yes - name: download apr_util file unarchive: src="{{ apr_url }}/{{ apr_util_version }}.tar.bz2" dest={{ download_dir }} owner=root remote_src=yes - name: prepare apr dir shell: chdir={{ download_dir }} mv {{ apr_version }} {{ download_dir }}/{{ httpd_version }}/srclib/apr - name: prepare apr_util dir shell: chdir={{ download_dir }} mv {{ apr_util_version }} {{ download_dir }}/{{ httpd_version }}/srclib/apr-util - name: build httpd shell: chdir={{ download_dir }}/{{ httpd_version }} ./configure --prefix={{ install_dir }} --enable-so \
--enable-ssl --enable-cgi --enable-rewrite --with-zlib --with-pcre --with-included-apr --enable-modules=most \
--enablempms-shared=all --with-mpm=prefork && make -j {{ ansible_processor_vcpus }} && make install - name: create group group: name=apache gid=80 system=yes - name: create user user: name=apache uid=80 group=apache shell=/sbin/nologin system=yes create_home=no home={{ install_dir }}/conf/httpd - name: set httpd user lineinfile: path={{ install_dir }}/conf/httpd.conf regexp='^User' line='User apache' - name: set httpd group lineinfile: path={{ install_dir }}/conf/httpd.conf regexp='^Group' line='Group apache' - name: set variable PATH shell: echo PATH={{ install_dir }}/bin:$PATH >> /etc/profile.d/httpd.sh - name: prepare service file template: src=./httpd.service.j2 dest=/usr/lib/systemd/system/httpd.service - name: start service service: name=httpd state=started enabled=yes
[root@ansible ansible]#cat httpd.service.j2 [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={{ install_dir }}/bin/apachectl start #ExecStart={{ install_dir }}/bin/httpd $OPTIONS -k start ExecReload={{ install_dir }}/bin/apachectl graceful #ExecReload={{ install_dir }}/bin/httpd $OPTIONS -k graceful ExecStop={{ install_dir }}/bin/apachectl stop KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target [root@ansible ansible]#ansible-playbook install_httpd.yml
httpd 常见配置
- 指定服务器域名
[root@centos8 ~]#vim /etc/httpd/conf/httpd.conf #ServerName www.example.com:80 servername www.chengzi.org
- 包含其它配置文件
Include file-path|directory-path|wildcard IncludeOptional file-path|directory-path|wildcard 说明: Include和IncludeOptional功能相同,都可以包括其它配置文件 但是当无匹配文件时,include会报错,IncludeOptional会忽略错误 #案例 #Wildcards may be included in the directory or file portion of the path. This example will fail if there is no subdirectory in conf/vhosts that contains at least one *.conf file: Include conf/vhosts/*/*.conf #Alternatively, the following command will just be ignored in case of missing files or directories: IncludeOptional conf/vhosts/*/*.conf
- 监听的IP和Port
Listen [IP:]PORT 说明: (1) 省略IP表示为本机所有IP (2) Listen指令至少一个,可重复出现多次 #案例 Listen 192.168.56.20:8080 Lsten 80
- 隐藏服务器版本信息
ServerTokens Major|Minor|Min[imal]|Prod[uctOnly]|OS|Full #案例: 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 (or not specified): Server: Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2 此为默认值 建议使用:ServerTokens Prod
- 禁止错误网页版本泄露
ServerSignature On | Off | EMail
默认值Off,如果ServerTokens 使用默认值,并且ServerSignature选项为on,当客户请求的网页并不存
在时,服务器将产生错误文档,错误文档的最后一行将包含服务器名字、Apache版本等信息,如果不对
外显示这些信息,就可将这个参数设置为Off, 如果设置为Email,将显示ServerAdmin 的Email提示
- 持久连接
Persistent Connection:连接建立,每个资源获取完成后不会断开连接,而是继续等待其它的请求完成,默认开启持久连接 说明: 1、时间限制:以秒为单位, 默认5s,httpd-2.4 支持毫秒级 2、请求数量: 请求数达到指定值,也会断开 3、副作用:对并发访问量大的服务器,持久连接会使有些请求得不到响应 4、折衷:使用较短的持久连接时间 #案例 KeepAlive On|Off KeepAliveTimeout 15 #连接持续15s,可以以ms为单位,默认值为5s MaxKeepAliveRequests 500 #持久连接最大接收的请求数,默认值100
- 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> #模块文件路径可使用相对路径:相对于ServerRoot(默认/etc/httpd) #查看静态编译的模块:httpd -l #查看静态编译及动态装载的模块:httpd -M [root@centos8 ~]#cat /etc/httpd/conf.modules.d/00-base.conf # # This file loads most of the modules included with the Apache HTTP # Server itself. # LoadModule access_compat_module modules/mod_access_compat.so LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule auth_basic_module modules/mod_auth_basic.so ...省略...
MPM (Multi-Processing Module) 多路处理模块
- httpd 支持三种MPM工作模式:prefork, worker, event
#启用要启用的MPM相关的LoadModule指令即可,其它未启用的两项需要在行首加#注释 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 #注意:不要同时启用多个MPM模块,否则会出现以下错误 AH00534: httpd: Configuration error: More than one MPM loaded.
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进程数 Upper limit on configurable number of processes StartServers 10 #Number of child server processes created at startup MaxRequestWorkers 150 #Maximum number of connections that will be processed simultaneously MinSpareThreads 25 #最小线程数 MaxSpareThreads 75 #最大线程数 ThreadsPerChild 25 #Number of threads created by each child process
定义Main server的文档页面路径
DocumentRoot "/path” <directory /path> Require all granted </directory> #说明: 1、DocumentRoot指向的路径为URL路径的起始位置 2、/path 必须显式授权后才可以访问
#案例 DocumentRoot "/data/html" <directory /data/html> Require all granted </directory> #URL和磁盘路径的映射关系 http://HOST:PORT/test/index.html --> /data/html/test/index.html
定义站点默认主页面文件
DirectoryIndex index.php index.html
定义路径别名
#格式 Alias /URL/ "/PATH/" #案例 [root@centos8 ~]#cat /etc/httpd/conf.d/test.conf alias /news /data/html/newsdir/ <directory /data/html/newsdir> require all granted </directory>
可实现访问控制的资源
- 文件系统路径:
#基于目录 <Directory "/path"> ... </Directory> #基于文件 <Files "/path/file”> ... </Files> #基于文件通配符 <Files "/path/*file*”> ... </Files> #基于扩展正则表达式 <FilesMatch "regex”> ... </FilesMatch> #案例 <FilesMatch ".+\.(gif|jpe?g|png)$"> # ... </FilesMatch> <Files ".ht*"> #通配符 Require all denied </
- URL路径:
<Location "URL"> ... </Location> <LocationMatch "regex"> ... </LocationMatch> #说明 #/private1, /private1/,/private1/file.txt 匹配 #/private1other 不匹配 <Location "/private1"> # ... </Location> #/private2/,/private2/file.txt 匹配 #/private2,/private2other 不匹配 <Location "/private2/"> # ... </Location> #案例 <Location /status> <LocationMatch "/(extra|special)/data">
针对目录和URL实现访问控制
(1) Options指令:
- 后跟1个或多个以空白字符分隔的选项列表, 在选项前的+,- 表示增加或删除指定选项
- 常见选项:
- Indexes:指明的URL路径下不存在与定义的主页面资源相符的资源文件时,返回索引列表给用户
- FollowSymLinks:允许访问符号链接文件所指向的源文件
- None:全部禁用
- All: 全部允许
#范例 <Directory /web/docs> Options -Indexes -FollowSymLinks </Directory> <Directory /web/docs/spec> Options -FollowSymLinks </Directory>
(2) AllowOverride指令
- 与访问控制相关的哪些指令可以放在指定目录下的.htaccess(由AccessFileName 指令指定,AccessFileName .htaccess 为默认值)文件中,覆盖之前的配置指令,只对语句有效
-
常见用法:
-
AllowOverride All: .htaccess中所有指令都有效
-
AllowOverride None: .htaccess 文件无效,此为httpd 2.3.9以后版的默认值
-
AllowOverride AuthConfig .htaccess 文件中,除了AuthConfig 其它指令都无法生效
-
vim /etc/httpd/conf/httpd.conf #Options Indexes FollowSymLinks Options Indexes #AllowOverride None AllowOverride options=FollowSymLinks,indexes #注释上一行,修改为此行
[root@centos8 ~]#vim /var/www/html/dir1/.htaccess Options FollowSymLinks indexes #加此行 [root@centos8 ~]#ln -s /app /var/www/html/dir1/applink [root@centos8 ~]#systemctl restart httpd
基于客户端 IP 地址实现访问控制
| 访问方式 |
1、客户端来源地址
2、用户账号
|
|
基于客户端的IP地址的访问控制
|
1、无明确授权的目录,默认拒绝
2、允许所有主机访问:Require all granted
3、拒绝所有主机访问:Require all denied
4、控制特定的IP访问:
Require ip IPADDR:授权指定来源的IP访问
Require not ip IPADDR:拒绝特定的IP访问
5、控制特定的主机访问:
Require host HOSTNAME:授权特定主机访问
Require not host HOSTNAME:拒绝
HOSTNAME:
FQDN:特定主机
domin.tld:指定域名下的所有主机
|
|
黑名单, 不能有失败,至少有一个成功匹配才成功,即失败优先
|
<RequireAll>
Require all granted
Require not ip 172.16.1.1 #拒绝特定IP
</RequireAll>
|
|
白名单, 多个语句有一个成功,则成功,即成功优先
|
<RequireAny>
Require all denied
require ip 172.16.1.1 #允许特定IP
</RequireAny>
|
http日志
- httpd有两种日志类型:访问日志、错误日志
- 访问日志
定义日志格式: LogFormat format nickname 使用日志格式: CustomLog file nickname #案例 LogFormat "%h %l %u [%{%F %T}t] \"%r\" %>s %b \"%{Referer}i\" \"%{UserAgent}i\"" testlog #说明 %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 #The contents of VARNAME: header line(s) in the request sent to the server
- 错误日志
LogLevel warn #LogLevel 可选值: debug, info, notice, warn,error, crit, alert, emerg ErrorLog logs/error_log
基于用户的访问控制
- 认证质询:WWW-Authenticate,响应码为401,拒绝客户端请求,并说明要求客户端需要提供账号和密码
-
认证:Authorization,客户端用户填入账号和密码后再次发送请求报文;认证通过时,则服务器发送响应的资源
-
认证方式两种:
-
basic:明文
-
digest:消息摘要认证,兼容性差
-
- 安全域:需要用户认证后方能访问的路径;应该通过名称对其进行标识,以便于告知用户认证的原因
- 用户的账号和密码
- 虚拟账号:仅用于访问某服务时用到的认证标识
- 存储:文本文件,SQL数据库,ldap目录存储,nis等
基于用户账号进行认证
- (1) 定义安全域
<Directory "/path"> Options None AllowOverride None AuthType Basic AuthName "String" #浏览器不同,可能这字符不一定能显示出来 AuthUserFile "/PATH/HTTPD_USER_PASSWD_FILE" Require valid-user #允许账号文件中的所有用户登录访问 #Require user username1 username2 ... 指定用户 </Directory>
- (2) 提供账号和密码存储(文本文件)
htpasswd [options] /PATH/HTTPD_PASSWD_FILE username password #示例 [root@centos7 ~]#htpasswd -cb /apps/httpd24/conf.d/.httpuser xiaoming 123zhongguo Adding password for user xiaoming
#需要确保apache用户对此文件要有read权限 setfacl -m u:apache:r /PATH/HTTPD_PASSWD_FILE #参数选项 -c 自动创建文件,仅应该在文件不存在时使用 -b 非交互方式创建用户,命令后面可以接密码 -p 明文密码 -d CRYPT格式加密,默认 -m md5格式加密 -s sha格式加密 -D 删除指定用户
#方法1
echo /var/www/html/admin/index.html > admin/index.html cat >/etc/httpd/conf.d/test.conf<<EOF <directory /var/www/html/admin> AuthType Basic AuthName "warning" AuthUserFile "/etc/httpd/conf.d/.httpuser" #Require user xiaoming xiaohong require valid-user </directory>
EOF
htpasswd -c /etc/httpd/conf.d/.httpuser xiaoming
htpasswd /etc/httpd/conf.d/.httpuser xiaohong cat /etc/httpd/conf.d/.httpuser
systemctl reload httpd curl http://xiaoming:centos@192.168.56.17/secret/
curl -u xiaohong:centos http://192.168.56.17/secret/
#方法2 mkdir /var/www/html/secret echo /var/www/html/secret/index.html >/var/www/html/secret/index.htmlcat >/var/www/html/secret/.htaccess<<EOF AuthType Basic AuthName "warning" AuthUserFile "/etc/httpd/conf.d/.httpuser" Require user xiaoming
EOFcat >/etc/httpd/conf.d/test.conf<<EOF <directory /var/www/html/admin> AuthType Basic AuthName "FBI warning" AuthUserFile "/etc/httpd/conf.d/.httpuser" #Require user xiaoming xiaohong require valid-user </directory> <directory /var/www/html/secret> allowoverride authconfig </directory>EOF
systemctl reload httpd
基于组账号进行认证
- (1) 定义安全域
<Directory "/path"> AuthType Basic AuthName "String" AuthUserFile "/PATH/HTTPD_USER_PASSWD_FILE" AuthGroupFile "/PATH/HTTPD_GROUP_FILE" Require group grpname1 grpname2 ... </Directory>
- 创建用户账号和组账号文件
#每行定义一个组
GRP_NAME: username1 username2 ...
cat >/etc/httpd/conf.d/test.conf<<EOF <directory /var/www/html/secret> allowoverride authconfig </directory>EOF
cat >/var/www/html/secret/.htaccess<<EOF AuthType Basic AuthName "FBI warning" AuthUserFile "/etc/httpd/conf.d/.httpuser" AuthGroupFile "/etc/httpd/conf.d/.httpgroup" Require group webadmins
EOF
cat /etc/httpd/conf.d/.httpuser cat /etc/httpd/conf.d/.httpgroup
status 状态页
- 此功能需要加载mod_status.so模块才能实现
LoadModule status_module modules/mod_status.so <Location "/status"> SetHandler server-status </Location> ExtendedStatus On #显示扩展信息,httpd 2.3.6以后版默认为On #确认加载mod_status.so模块 [root@centos8 conf.d]#httpd -M |grep status status_module (shared)
- 对status页面进行登录认证
cat >/apps/httpd24/conf.d/test.conf<<EOF <Location "/status"> AuthType Basic AuthName "Please login" AuthUserFile "/apps/httpd24/conf.d/.httpuser" Require user xiaohong SetHandler server-status </Location>
EOF
多虚拟主机
多虚拟主机有三种实现方案: 基于ip:为每个虚拟主机准备至少一个ip地址 基于port:为每个虚拟主机使用至少一个独立的port 基于FQDN:为每个虚拟主机使用至少一个FQDN,请求报文中首部 Host: www.chengzi.com 注意:httpd 2.4版本中,基于FQDN的虚拟主机不再需要NameVirutalHost指令
虚拟主机的基本配置方法
<VirtualHost IP:PORT> ServerName FQDN DocumentRoot "/path" </VirtualHost> 建议:上述配置存放在独立的配置文件中,降低配置文件的耦合度 其它常用可用指令: ServerAlias:虚拟主机的别名;可多次使用 ErrorLog: 错误日志 CustomLog:访问日志 <Directory "/path"> </Directory>
基于端口的虚拟主机
echo /data/website1/index.html >/data/website1/index.html echo /data/website2/index.html >/data/website2/index.html echo /data/website3/index.html >/data/website3/index.html cat >/etc/httpd/conf.d/test.conf<<EOF listen 8001 listen 8002 listen 8003 <virtualhost *:8001> documentroot /data/website1/ CustomLog logs/website1_access.log combined <directory /data/website1> require all granted </directory> </virtualhost>
<virtualhost *:8002> documentroot /data/website2/ CustomLog logs/website2_access.log combined <directory /data/website2> require all granted </directory> </virtualhost>
<virtualhost *:8003> documentroot /data/website3/ CustomLog logs/website3_access.log combined <directory /data/website3> require all granted </directory> </virtualhost> EOF ##浏览器访问不同端口,得到不同的页面 curl http://192.168.56.18:8001/ curl http://192.168.56.18:8002/ curl http://192.168.56.18:8003/
基于IP的虚拟主机
ip a a 192.168.56.8/24 dev eth0 label eth0:1 ip a a 192.168.56.18/24 dev eth0 label eth0:2 ip a a 192.168.56.28/24 dev eth0 label eth0:3
cat >/etc/httpd/conf.d/test.conf<<EOF #listen 8001 #listen 8002 #listen 8003 <virtualhost 192.168.56.8:80> documentroot /data/website1/ CustomLog logs/website1_access.log combined <directory /data/website1> require all granted </directory> </virtualhost> <virtualhost 192.168.56.18:80> documentroot /data/website2/ CustomLog logs/website2_access.log combined <directory /data/website2> require all granted </directory> </virtualhost> <virtualhost 192.168.56.28:80> documentroot /data/website3/ CustomLog logs/website3_access.log combined <directory /data/website3> require all granted </directory> </virtualhost> EOF
基于FQDN虚拟主机
cat >/etc/httpd/conf.d/test.conf<<EOF
<VirtualHost *:80> ServerName www.a.com DocumentRoot "/www/a.com/htdocs" <Directory "/www/a.com/htdocs"> ErrorLog "logs/a_error_log" CustomLog "logs/a_access_log" combined Options None AllowOverride None Require all granted </Directory>
</VirtualHost> <VirtualHost *:80> ServerName www.b.net DocumentRoot "/www/b.net/htdocs" <Directory "/www/b.net/htdocs"> ErrorLog "logs/b_error_log" CustomLog "logs/b_access_log" combined Options None AllowOverride None Require all granted </Directory> </VirtualHost>
<VirtualHost *:80> ServerName www.c.org DocumentRoot "/www/c.org/htdocs" <Directory "/www/c.org/htdocs"> ErrorLog "logs/c_error_log" CustomLog "logs/c_access_log" combined Options None AllowOverride None Require all granted </Directory> </VirtualHost>
EOF
注意: 1、任意目录下的页面只有显式授权才能被访问 2、三种方式的虚拟主机可以混和使用 3、基于主机头的第一个虚拟主机将成为默认站点
压缩
- 使用mod_deflate模块压缩页面优化传输速度
LoadModule deflate_module modules/mod_deflate.so SetOutputFilter
- 适用场景
- 节约带宽,额外消耗CPU;同时,可能有些较老浏览器不支持
- 压缩适于压缩的资源,例如文本文件
#可选项 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

浙公网安备 33010602011771号