前言:
http服务器程序:httpd(apache), nginx, lighttpd。(处理静态内容)
应用程序服务器:IIS:.NET tomcat: .jsp (能够处理动态内容)
===============================================分割线======================================
httpd的特性:
(1)高度模块化:core+modules
(2)DSO机制:dynamic shared object(动态共享对象,可以支持动态装卸载模块)
(3)MPM:Multipath processing Modules(多路处理模块)
①prefork:多进程模型,每个进程响应一个请求。
一个主进程:负责生成子进程以处理用户请求,并回收子进程,负责创 建套接字,不处理请求,只将请求派发给某子进程进行处 理;
多个子进程:每个子进程处理一个请求;
工作模型:会预先生成几个空闲进程,随时等待用于响应用户请求,并 提前定义最大空闲和最小空闲;
②worker:多进程多线程模型,每一个线程处理一个用户请求;
一个主进程:负责生成子进程以处理用户请求,并回收子进程,负责创 建套接字,不处理请求,只将请求派发给某子进程进行处 理;
多个子进程:每个子进程负责生成多个线程;
每个线程:负责处理用户请求;
并发相应数量:m(子进程数量)*n(每个子进程所能创建的最大线程数 量)
③event:事件驱动模型(多进程模型),每个进程响应多个请求。
一个主进程:负责生成子进程以处理用户请求,并回收子进程,负责创 建套接字,不处理请求,只将请求派发给某子进程进行处 理;
子进程:基于事件驱动机制直接响应多个请求;
http-2.2中为测试使用模型,2.4可在生产环境中使用。
http的程序版本:
http 1.3、2.0、2.2、2.4(目前最新稳定版)
http的功能:
①CGI:Common Gateway Interface(通用网关接口)
②虚拟主机:IP,PORT,FQDN
③反向代理
④负载均衡机制
⑤路径别名
⑥丰富的用户认证机制(basic,digest)
⑦支持第三方模块
.....
安装http:
rpm包:CentOS发行版中直接提供
编译安装:定制新功能,补漏洞等其他原因采用。
httpd的程序环境:
CentOS 6:http-2.2
配置文件:/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/*.conf
服务脚本:/etc/rc.d/init.d/httpd
脚本配置文件:/etc/sysconfig/httpd
主程序文件:/usr/sbin/httpd (prefork)默认
/usr/sbin/http.event
/usr/sbin/http.worker
日志文件:/var/log/httpd:
access_log:访问日志
error_log:错误日志
站点文档:/var/www/html
模块文件路径:/usr/lib64/httpd/modules
服务控制和启动:chkconfig http on|off
service {start|stop|restart|status|configtest|reload} httpd
CentOS 7:httpd-2.4
配置文件:
/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/*.conf
模块相关的配置文件:/etc/httpd/conf.modules.d/*.conf
systemd unit file:
/usr/lib/systemd/system/httpd.service
主程序文件:
/usr/sbin/httpd
httpd-2.4支持MPM的动态切换;
日志文件:
/var/log/httpd:
access_log:访问日志
error_log:错误日志
站点文档:
/var/www/html
模块文件路径:
/usr/lib64/httpd/modules
服务控制:
systemctl enable|disable httpd.service
systemctl {start|stop|restart|status} httpd.service
=============================================分割线========================================
httpd-2.2的常用配置:
主配置文件:/etc/httpd/conf/httpd.conf
### Section 1: Global Environment(全局配置段)
### Section 2: 'Main' server configuration(中心主机配置段)
### Section 3: Virtual Hosts(虚拟主机配置段)
(注:第二段和第三段不能同时使用,默认使用第二段)
配置格式:
directive value
directive:不区分字符大小写;
value:为路径时,是否区分字符大小写,取决于文件系统;
常用配置:
1、修改监听的IP和PORT
Listen [IP:]PORT
①省略IP表示为0.0.0.0
②Listen指令可重复出现多次
Listen 80
Listen 8080
(注:修改完需要重启服务)
# # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, in addition to the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses (0.0.0.0) # #Listen 12.34.56.78:80 Listen 80 Listen 8080 #增加监听端口 [root@Tzz conf]# service httpd restart #重启服务 [root@Tzz conf]# netstat -tnpl | grep "httpd" tcp 0 0 :::8080 :::* LISTEN 3020/httpd tcp 0 0 :::80 :::* LISTEN 3020/httpd
2、持久连接
Persistent Connection:tcp连续建立连接后,每个资源获取完成后不全断开连接,而是继 续等待其他资源请求的进行
如何断开连接:数量限制、时间限制
(注:这种长连接机制会使并发访问量较大的服务器后续的某些请求无法得到正常访问)
我们可以使用较短的持久连接时长,以及较少的请求数量;
# KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive on #表示打开持久连接选项 # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 #持久连接的请求数量不能超过100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 15 #持久连接的时间不能超过15秒
3、MPM
http-2.2不支持同时编译多个MPM模块,所以只能编译选择要使用的MPM模块;CentOS 6的rpm包为此专门提供了三个应用程序文件,httpd(prefork)默认使用的MPM模块, httpd.worker, httpd.event,分别用于实现对不同的MPM机制的支持;确认现在使用的是哪下程序文件的方法:
[root@Tzz conf]# ps aux | grep "httpd" root 3446 0.0 0.8 185928 3900 ? Ss 09:50 0:00 /usr/sbin/httpd apache 3449 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd apache 3450 0.0 0.5 186060 2516 ? S 09:50 0:00 /usr/sbin/httpd apache 3451 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd apache 3452 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd apache 3453 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd apache 3454 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd apache 3455 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd apache 3456 0.0 0.5 186060 2496 ? S 09:50 0:00 /usr/sbin/httpd root 3458 0.0 0.1 103308 852 pts/0 S+ 09:50 0:00 grep httpd
[root@Tzz conf]# /usr/sbin/httpd -l #查看静态编译的模块: Compiled in modules: core.c prefork.c http_core.c mod_so.c
[root@Tzz conf]# /usr/sbin/httpd -M #查看静态编译及动态编译的模块 Loaded Modules: core_module (static) mpm_prefork_module (static) http_module (static) so_module (static) auth_basic_module (shared) auth_digest_module (shared) authn_file_module (shared) authn_alias_module (shared) authn_anon_module (shared) authn_dbm_module (shared) authn_default_module (shared) authz_host_module (shared) authz_user_module (shared) authz_owner_module (shared) authz_groupfile_module (shared) authz_dbm_module (shared) authz_default_module (shared) ldap_module (shared) authnz_ldap_module (shared) include_module (shared) log_config_module (shared) logio_module (shared) env_module (shared) ext_filter_module (shared) mime_magic_module (shared) expires_module (shared) deflate_module (shared) headers_module (shared) usertrack_module (shared) setenvif_module (shared) mime_module (shared) dav_module (shared) status_module (shared) autoindex_module (shared) info_module (shared) dav_fs_module (shared) vhost_alias_module (shared) negotiation_module (shared) dir_module (shared) actions_module (shared) speling_module (shared) userdir_module (shared) alias_module (shared) substitute_module (shared) rewrite_module (shared) proxy_module (shared) proxy_balancer_module (shared) proxy_ftp_module (shared) proxy_http_module (shared) proxy_ajp_module (shared) proxy_connect_module (shared) cache_module (shared) suexec_module (shared) disk_cache_module (shared) cgi_module (shared) version_module (shared) dnssd_module (shared) Syntax OK
更换使用httpd程序,以支持其它MPM机制;
[root@Tzz conf]# vim /etc/sysconfig/httpd # Configuration file for the httpd service. # # The default processing model (MPM) is the process-based # 'prefork' model. A thread-based model, 'worker', is also # available, but does not work with some modules (such as PHP). # The service must be stopped before changing this variable. # HTTPD=/usr/sbin/httpd.worker #修改时先关闭服务(httpd-2.2不支持event模式) [root@Tzz conf]# ps aux | grep "httpd" root 3298 0.0 0.8 186136 4116 ? Ss 09:48 0:00 /usr/sbin/httpd.worker apache 3301 0.0 0.6 530396 3348 ? Sl 09:48 0:00 /usr/sbin/httpd.worker apache 3303 0.0 0.6 530396 3340 ? Sl 09:48 0:00 /usr/sbin/httpd.worker apache 3304 0.0 0.6 530396 3340 ? Sl 09:48 0:00 /usr/sbin/httpd.worker root 3414 0.0 0.1 103308 852 pts/0 S+ 09:48 0:00 grep httpd
MPM的配置:
prefork的配置
[root@Tzz conf]# vim httpd.conf # prefork MPM # StartServers: number of server processes to start # MinSpareServers: minimum number of server processes which are kept spare # MaxSpareServers: maximum number of server processes which are kept spare # ServerLimit: maximum value for MaxClients for the lifetime of the server # MaxClients: maximum number of server processes allowed to start # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule prefork.c> StartServers 8 #服务器启动时默认开启的进程数目 MinSpareServers 5 #最少空闲进程数 MaxSpareServers 20 #最大空闲进程 ServerLimit 256 #允许启动的最大在线进程数量 MaxClients 256 #最大并发响应数量 MaxRequestsPerChild 4000 #每个子进程可以处理的最大请求数量 </IfModule>
worker的配置:
[root@Tzz conf]# vim httpd.conf # worker MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule worker.c> StartServers 4 #默认启动进程数 MaxClients 300 #最大并发响应数量 MinSpareThreads 25 #最小空闲线程数量 MaxSpareThreads 75 #最大空闲线程数量 ThreadsPerChild 25 #每个进程最大可以生成的线程 MaxRequestsPerChild 0 #每个线程能处理的最大请求数量(0表示无限 </IfModule>
( PV,UV
PV:Page View
UV: User View )
4、DSO(动态共享对象)
配置指定配置文件实现模块加载
LoadModule <mod_name> <mod_path>
模块文件路径可使用相对路径:
相对于ServerRoot(默认/etc/httpd)
# # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule auth_digest_module modules/mod_auth_digest.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authn_alias_module modules/mod_authn_alias.so LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_dbm_module modules/mod_authn_dbm.so #已经装载的模块(没完整列出) # The following modules are not loaded by default: # #LoadModule asis_module modules/mod_asis.so #LoadModule authn_dbd_module modules/mod_authn_dbd.so #LoadModule cern_meta_module modules/mod_cern_meta.so #LoadModule cgid_module modules/mod_cgid.so #LoadModule dbd_module modules/mod_dbd.so #LoadModule dumpio_module modules/mod_dumpio.so #LoadModule filter_module modules/mod_filter.so #LoadModule ident_module modules/mod_ident.so #LoadModule log_forensic_module modules/mod_log_forensic.so #LoadModule unique_id_module modules/mod_unique_id.so #没有装载的模块
5、中心主机,定义‘Main'server的文档页面路径
DocumentRoot ""
文档路径映射:
DoucmentRoot指向的路径为URL路径的起始位置
其相当于站点URL的根路径:
例如:(FileSystem) /web/host1/index.html --> (URL) /index.html
# # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/var/www/html" #此为访问页面URL的根目录
修改访问页面的根目录:
# # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/web/host1" #此处修改为我提前创建好的目录 [root@Tzz conf]# vim /web/host1/index.html <h1>New Location</h1> #此为我修改后的页面文档内容 [root@Tzz conf]# service httpd reload Reloading httpd:
验证结果:
更改完配置文件中的中心文档页面路径之后主页面就会显示我们事先预定好的页面文档内容。
6、站点访问控制常见机制
可基于两种机制指明对哪些资源进行何种访问控制
①文件系统路径:
<Directory "">
....
</Directory>
<File "">
....
</File>
②URL路径:
<Location "">
....
</Location>
<Directory>中“基于源地址”实现访问控制:
<Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Order allow,deny Allow from all </Directory>
(1) Options:后跟1个或多个以空白字符分隔的“选项”列表;
# # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks
1)Indexes:指明的URL路径下不存在与定义的主页面资源相符的资源文件时,返回索引列 表给用户;(明确该页面为下载站点时启用)
2)FollowSymLinks:允许跟踪符号链接文件所指向的源文件;
3)None
4)All
测试Idexes的结果:
<Directory "/web/host1"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks [root@Tzz conf]# service httpd reload Reloading httpd:
Options中如果有Indexes选项时,当你查找的请求没有对应资源时就会返回请求路径下的文件列表,如下图所示:(此种方法不安全,当网站中存放有重要数据时返回出来的数据就能被用户随意查看了,只有在下载页面上才有必要开启此功能)
把该选项去掉后就会提示没有权限:
Options FollowSymLinks
测试FollowSymLinks选项:
[root@Tzz host1]# ln -sv /etc/fstab /web/host1/test2.html #在根URL下创建fstab的符号链接 `/web/host1/test2.html' -> `/etc/fstab' [root@Tzz host1]# ll total 4 lrwxrwxrwx 1 root root 10 Jan 12 12:00 test2.html -> /etc/fstab -rw-r--r-- 1 root root 23 Jan 12 10:34 test.html [root@Tzz host1]# service httpd reload Reloading httpd:
(2) AllowOverride
与访问控制相关的哪些指令可以放在.htaccess文件中(每个目录下都可以有一个);
但会降低网页解析性能
# # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None
1)All:
2)None:
(3) order和allow、deny
order:定义生效次序;写在后面的表示默认法则;
Allow from, Deny from
来源地址:
IP
NetAddr:
172.16
172.16.0.0
172.16.0.0/16
172.16.0.0/255.255.0.0
# # Controls who can get stuff from this server. # Order allow,deny Allow from all
7、定义站点主页面
# # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # # The index.html.var file (a type-map) is used to deliver content- # negotiated documents. The MultiViews Option can be used for the # same purpose, but it is much slower. # DirectoryIndex index.html index.html.var #默认为这两个文件为主页面
8、定义路径别名(路径映射)
格式:Alias /URL/ "/PATH/TO/SOMEFILE"
定义路径别名:
[root@Tzz conf]# mkdir /web/host1/download [root@Tzz conf]# cd /web/host1/download [root@Tzz download]# vim index.html <h1>/web/host1/download</h1> [root@Tzz download]# mkdir -pv /www/host1 mkdir: created directory `/www' mkdir: created directory `/www/host1' [root@Tzz download]# vim /www/host1/index.html <h1>/www/host1</h1>
[root@Tzz download]# cd /etc/httpd/conf [root@Tzz conf]# vim httpd.conf Alias /icons/ "/var/www/icons/" Alias /download/ "/www/host1/" [root@Tzz conf]# service httpd reload Reloading httpd:
9、设定默认字符集
# # Specify a default charset for all content served; this enables # interpretation of all content as UTF-8 by default. To use the # default browser choice (ISO-8859-1), or to allow the META tags # in HTML content to override this choice, comment out this # directive: # AddDefaultCharset UTF-8
中文字符集:GBK, GB2312, GB18030
10、日志设定
日志类型:访问日志和错误日志
错误日志:ErrorLog
LogLevel: warn
Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
# ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog logs/error_log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn
访问日志:
# For a single logfile with access, agent, and referer information # (Combined Logfile Format), use the following directive: # CustomLog logs/access_log combined #combined指明日志格式 # 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\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent
LogFormat strings:
%h:客户端IP地址
%l:远程用户名,通常为“-”
%u:远程用户,非为登录访问时,其为一个减号“-”
%t:服务器收到请求时的时间,标准英文格式的时间
%r:请求报文的首行,记录了此次请求的“方法”,“URL”以及协议版本;
%>s:响应状态码;
%b:响应报文的大小,单位为bytes,不包括响应报文的http首部;
%{Referer}i:表示请求报文中首部“Referer”的值;即从那个页面中的超链接跳转至当前页面的
%{User-Agent}i:请求报文中首部“User-Agent”的值,即发出请求的应用程序。
[root@Tzz conf]# cat /var/log/httpd/access_log 172.16.250.24 - - [11/Jan/2016:08:48:01 +0800] "GET / HTTP/1.1" 403 4961 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" 172.16.250.24 - - [11/Jan/2016:08:48:01 +0800] "GET /icons/apache_pb.gif HTTP/1.1" 200 2326 "http://172.16.249.147/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" 172.16.250.24 - - [11/Jan/2016:08:48:01 +0800] "GET /icons/poweredby.png HTTP/1.1" 200 3956 "http://172.16.249.147/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" 172.16.250.24 - - [11/Jan/2016:08:48:01 +0800] "GET /favicon.ico HTTP/1.1" 404 289 "http://172.16.249.147/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" 172.16.250.24 - - [11/Jan/2016:08:52:54 +0800] "GET / HTTP/1.1" 403 4961 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" 172.16.250.24 - - [11/Jan/2016:09:29:10 +0800] "GET / HTTP/1.1" 403 4961 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" 172.16.250.24 - - [12/Jan/2016:07:02:04 +0800] "GET / HTTP/1.1" 403 4961 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"
11、基于用户的访问控制(http协议认证)
认证质询:WWW-AUthenticate:响应码为401,拒绝客户端请求,并说明要求客户端提供帐号和密码;
认证:Authorization:客户端用户填入帐号和密码后再次发送请求报文;认证通过时,服务器发送响应的资源。
认证方式:basic:明文
digest:消息摘要认证;
安全域:需要用户认证后方能访问的路径,应该通过名称对其进行标识,以便于告知用户认证的原因;
用户的账号和密码存放于何处
虚拟账号:仅用于访问某服务时用到的认证标识
存储:
文本文件;
SQL数据库;
ldap(轻量级)目录存储;
basic认证配置示例:
(1)定义安全域
[root@Tzz conf]# mkdir /web/host1/admin #根URL下创建用户空间目录 [root@Tzz conf]# vim /web/host1/admin/index.html [root@Tzz conf]# vim /web/host1/admin/index.html <h1>Admin Page</h1> [root@Tzz conf]# vim httpd.conf #编辑配置文件定义安全域 <Directory "/web/host1/admin"> Options None AllowOverride None Authtype Basic #认证方式 AuthName "Important File! Please Offer U ID" #定义认证名称内容 AuthUserFile "/etc/httpd/conf/.htpasswd" #认真呢个用户的帐号和密码的文本文件 Require user tzz job tracy #允许访问的用户帐号 # Require valid-user #允许所有用户访问 </Directory> [root@Tzz conf]# service httpd reload Reloading httpd:
测试结果:
(2)提供帐号和密码存储(文本文件)
用专用命令完成此类文件的创建及用户管理
htpasswd [options] /PATH/TO/HTTPD_PASSWD_FILE username
-c:自动创建此处指定的文件,因此,仅应该在此文件不存在时使用;
-m:md5格式加密
-s: sha格式加密
-D:删除指定用户
[root@Tzz conf]# htpasswd -m -c /etc/httpd/conf/.htpasswd tzz #首次创建要加-c New password: Re-type new password: Adding password for user tzz [root@Tzz conf]# htpasswd -m /etc/httpd/conf/.htpasswd job New password: Re-type new password: Adding password for user job [root@Tzz conf]# htpasswd -m /etc/httpd/conf/.htpasswd tracy New password: Re-type new password: Adding password for user tracy [root@Tzz conf]# htpasswd -m /etc/httpd/conf/.htpasswd tom New password: Re-type new password: Adding password for user tom
基于组帐号进行认证:
(1)定义安全域:
<Directory "/web/host1/admin"> Options None AllowOverride None Authtype Basic AuthName "Important File! Please Offer U ID" AuthUserFile "/etc/httpd/conf/.htpasswd" AuthGroupFile "/etc/httpd/conf/.htgroup" #定义认证组文件 Require group mygroup #定义允许访问的组 # Require valid-user </Directory> [root@Tzz conf]# vim /etc/httpd/conf/.htgroup mygroup: job tracy #定义组名和组内的账户 [root@Tzz conf]# httpd -t Syntax OK [root@Tzz conf]# service httpd reload
测试结果:
12、虚拟主机
站点标识:socket
(1)IP相同PORT不同;
(2)IP不同PORT为默认端口;
(3)FQDN不同:根据请求报文的http首部不同进行解析,而不再根据IP首部进行解析,Host
实现方案:
基于Ip:为每个虚拟主机准备至少一个IP地址;
基于PORT:为每个虚拟主机使用至少一个独立的PORT;
基于FQDN:为每个虚拟主机使用至少一个FQDN;
(注意:一般虚拟机不要与中心主机混用;因此,要使用虚拟主机,得先禁用'main'主机;)
禁用方法:注释中心主机的DocumentRoot指令即可。
第一种方案:
eth0:0 Link encap:Ethernet HWaddr 00:0C:29:5A:42:5E inet addr:172.16.61.66 Bcast:172.16.255.255 Mask:255.255.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 eth0:1 Link encap:Ethernet HWaddr 00:0C:29:5A:42:5E inet addr:172.16.61.88 Bcast:172.16.255.255 Mask:255.255.0.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 #为eth0网卡增加了两个IP地址 [root@Tzz conf]# mkdir -pv /www/{a.com,b.com,c.com} #提前做好三个主页面路径 mkdir: created directory `/www/a.com' mkdir: created directory `/www/b.com' mkdir: created directory `/www/c.com' [root@Tzz conf]# vim /www/a.com/index.html #创建主页面文件 <h1>www/a.com</h1> [root@Tzz conf]# vim /www/b.com/index.html #创建主页面文件 <h1>www.b.com</h1> [root@Tzz conf]# vim /www/c.com/index.html #创建主页面文件 <h1>www.b.com</h1> # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # #DocumentRoot "/web/host1" #注释掉中心主机 [root@Tzz conf]# vim /etc/httpd/conf.d/vhost.conf #我们可以在/conf.d/下专门创建文件用来定义虚拟主机,方便我们管理,只要在conf.d下的以.conf结尾的都可以被配置文件识别 <VirtualHost 172.16.249.147:80> ServerName www.a.com DocumentRoot "/www/a.com" </VirtualHost> <VirtualHost 172.16.61.66:80> ServerName www.b.com DocumentRoot "/www/b.com" </VirtualHost> <VirtualHost 172.16.61.88:80> ServerName www.c.com DocumentRoot "/www/c.com" </VirtualHost> [root@Tzz conf]# httpd -t #检查配置文件语法是否有错误 Syntax OK [root@Tzz conf]# service httpd reload Reloading httpd:
测试结果:
第二种方案:
[root@Tzz conf]# vim /etc/httpd/conf.d/vhost.conf Listen 8080 #监听于8080端口 Listen 808 #监听于808端口 <VirtualHost 172.16.249.147:8080> #根据端口定义虚拟主机 ServerName www.a.com DocumentRoot "/www/a.com" </VirtualHost> <VirtualHost 172.16.249.147:80> ServerName www.b.com DocumentRoot "/www/b.com" </VirtualHost> <VirtualHost 172.16.249.147:808> ServerName www.c.com DocumentRoot "/www/c.com" </VirtualHost> [root@Tzz conf]# service httpd restart #重新更改监听地址后要重启而不是重载 Stopping httpd: [ OK ] Starting httpd: [ OK ] [root@Tzz conf]# ss -tan #确保80 8080 808 端口都处于监听状态 State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 :::808 :::* LISTEN 0 128 :::50861 :::* LISTEN 0 128 :::111 :::* LISTEN 0 128 *:111 *:* LISTEN 0 128 :::8080 :::* LISTEN 0 128 :::80 :::*
测试结果:
(注:也可以将IP和PORT混合使用)
第三种方案:基于FQDN的虚拟主机
[root@Tzz conf]# vim /etc/httpd/conf.d/vhost.conf #表示使用FQDN使用虚拟主机 NameVirtualHost 172.16.249.147:80 <VirtualHost 172.16.249.147:80> ServerName www.a.com DocumentRoot "/www/a.com" </VirtualHost> <VirtualHost 172.16.249.147:80> ServerName www.b.com DocumentRoot "/www/b.com" </VirtualHost> <VirtualHost 172.16.249.147:80> ServerName www.c.com DocumentRoot "/www/c.com" </VirtualHost> [root@Tzz conf]# httpd -t Syntax OK [root@Tzz conf]# service httpd reload Reloading httpd:
测试结果:
由于该操作都在虚拟主机中设定,需要将windows系统的hosts文件增加FQDN的解析才行
13、status页面
<Location /server-status> #启用该模块 SetHandler server-status Order allow deny Allow from all #并设置访问控制 </Location> [root@Tzz conf]# httpd -t Syntax OK[root@Tzz conf]# service httpd reload Reloading httpd:
测试结果:
==============================================未完待续=====================================
=========================================一月十三续========================================
14、curl命令
curl是基于URL语法在命令行方式下工作的文件传输工具,它支持FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE及LDAP等协议。curl支持HTTPS认证,并且支持HTTP的POST、PUT等方法, FTP上传, kerberos认证,HTTP上传,代理服务器, cookies, 用户名/密码认证, 下载文件断点续传,上载文件断点续传, http代理服务器管道( proxy tunneling), 甚至它还支持IPv6, socks5代理服务器,,通过http代理服务器上传文件到FTP服务器等等,功能十分强大。
用法:curl [options] [URL...]
curl的常用选项:
-A/--user-agent <string>: 设置用户代理发送给服务器
--basic :使用HTTP基本认证
--tcp-nodelay :使用TCP_NODELAY选项
-e/--referer <URL>: 来源网址
--cacert <file> :CA证书 (SSL)
--compressed :要求返回是压缩的格式
-H/--header <line>:自定义首部信息传递给服务器
-I/--head :只显示响应报文首部信息
--limit-rate <rate>: 设置传输速度
-u/--user <user[:password]>:设置服务器的用户和密码
-0/--http1.0 :使用HTTP 1.0
[root@Tzz ~]# curl http://172.16.249.147/index.html <h1> [root@Tzz ~]# curl -A ie6 #装做ie6 <h1>www.a.com</h1> [root@Tzz ~]# curl -I #只显示首部信息,相当于HEAD方法 HTTP/1.1 200 OK Date: Wed, 13 Jan 2016 09:00:56 GMT Server: Apache/2.2.15 (CentOS) Last-Modified: Tue, 12 Jan 2016 08:39:23 GMT ETag: "6000c-13-5291efd959e3a" Accept-Ranges: bytes Content-Length: 19 Connection: close Content-Type: text/html; charset=UTF-8
另一个工具:elinks(全屏的文本浏览器工具,完全模拟浏览器访问服务器)
elinks [OPTION]... [URL]...
-dump: 不进入交互式模式,而直接将URL的内容输出至标准输出;
[root@Tzz ~]# elinks
[root@Tzz ~]# elinks -dump http://172.16.249.147/index.html www.a.com
15、user/group
用于指定用哪个用户的身份运行httpd服务进程;
为了系统自身的安全性,当httpd运行时都以系统用户和系统组的身份运行。
User: apache
Group: apache
# If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # . On SCO (ODT 3) use "User nouser" and "Group nogroup". # . On HPUX you may not be able to use shared memory as nobody, and the # suggested workaround is to create a user www and use that user. # NOTE that some kernels refuse to setgid(Group) or semctl(IPC_SET) # when the value of (unsigned)Group is above 60000; # don't use Group #-1 on these systems! # User apache Group apache
当有些页面指定需要管理员身份运行时,我们就需要使用SUexec机制进行用户切换。
16、使用mod_deflate模块压缩页面优化传输速度
[root@Tzz conf]# httpd -M | grep deflate Syntax OK deflate_module (shared)
适用场景:
(1) 节约带宽,额外消耗CPU;同时,可能有些较老浏览器不支持;
(2) 压缩适于压缩的资源,例如文件文件;
SetOutputFilter DEFLATE(设置输出过滤器)
# Restrict compression to these MIME types
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
# Level of compression (Highest 9 - Lowest 1)(压缩级别,级别越高压缩比越大)
DeflateCompressionLevel 9
# Netscape 4.x has some problems. (排除不支持的浏览器)
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
[root@Tzz conf]# vim httpd.conf #配置文件中加入压缩选项 #DEFLATE SetOutputFilter DEFLATE # Restrict compression to these MIME types 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 # Level of compression (Highest 9 - Lowest 1) DeflateCompressionLevel 9 #指定压缩级别 [root@Tzz conf]# httpd -t Syntax OK [root@Tzz conf]# service httpd reload Reloading httpd: [root@Tzz a.com]# ll #复制一个较大的文件到当前根文档目录下 total 8 -rw-r--r-- 1 root root 19 Jan 12 16:39 index.html -rw-r--r-- 1 root root 1656 Jan 14 03:53 passwd.html
在浏览器上请求该页面打开开发者选项,找到响应报文的首部就能看到请求内容的编码格式
17、https,http over ssl
配置httpd支持https:
(1) 为服务器申请数字证书;
测试:通过私建CA发证书
(a) 创建私有CA
(b) 在服务器创建证书签署请求
(c) CA签证
(2) 配置httpd支持使用ssl,及使用的证书;
# yum -y install mod_ssl
配置文件:/etc/httpd/conf.d/ssl.conf
DocumentRoot
ServerName
SSLCertificateFile
SSLCertificateKeyFile
(3) 测试基于https访问相应的主机;
# openssl s_client [-connect host:port] [-cert filename] [-CApath directory] [-CAfile filename]
测试:
第一步:在新的主机上创建私有CA:
[root@localhost ~]# (umask 077; openssl genrsa -out /etc/pki/CA/private/cakey.pem 2048) Generating RSA private key, 2048 bit long modulus .............................+++ ..................+++ e is 65537 (0x10001) #生成CA的私钥
第二步:生成CA的自签证书:
[root@localhost ~]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:beijing Locality Name (eg, city) [Default City]:beijing Organization Name (eg, company) [Default Company Ltd]:mageedu Organizational Unit Name (eg, section) []:ops Common Name (eg, your name or your server's hostname) []:ca.mageedu.com Email Address []:[email protected]
第三步:提供CA所需要的目录及文件:
[root@localhost ~]# ls /etc/pki/CA/ cacert.pem certs crl newcerts private [root@localhost ~]# touch /etc/pki/CA/{serial,index.txt} [root@localhost ~]# echo 01 > /etc/pki/CA/serial
第四步:web服务器向CA请求证书:
[root@Tzz httpd]# mkdir ssl
[root@Tzz httpd]# cd ssl
[root@Tzz httpd]# (umask 077; openssl genrsa -out httpd.key 1024) #为httpd创建私钥
Generating RSA private key, 1024 bit long modulus
.......................................++++++
........................++++++
e is 65537 (0x10001)
[root@Tzz ssl]# openssl req -new -key httpd.key -out httpd.csr #在web服务器上生成签署请求
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:beijing
Locality Name (eg, city) [Default City]:beijing
Organization Name (eg, company) [Default Company Ltd]:mageedu
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:www.magedu.com
Email Address []:[email protected]
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@Tzz ssl]# scp httpd.csr [email protected]:/tmp #将证书签署请求发送给CA
[email protected]'s password:
第五步:CA对服务器签署证书请求
[root@localhost ~]# openssl ca -in /tmp/httpd.csr -out /etc/pki/CA/certs/httpd.crt #在CA端签署证书 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: Jan 14 02:01:32 2016 GMT Not After : Jan 13 02:01:32 2017 GMT Subject: countryName = CN stateOrProvinceName = beijing organizationName = mageedu organizationalUnitName = ops commonName = www.magedu.com emailAddress = [email protected] X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 0A:F1:7B:39:EB:92:E8:AC:B7:2C:4E:5C:1D:52:31:08:70:30:DA:FB X509v3 Authority Key Identifier: keyid:1B:E0:A4:6C:74:81:05:B3:AC:B8:CC:36:90:7A:22:AF:3E:41:3D:BB Certificate is to be certified until Jan 13 02:01:32 2017 GMT (365 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated [root@localhost ~]# scp /etc/pki/CA/certs/httpd.crt @172.16.249.147:/etc/httpd/ssl #将签署过的证书发送个服务器端 [email protected]'s password: httpd.crt 100% 3836 3.8KB/s 00:0 [root@Tzz ssl]# ls #服务器端 httpd.crt httpd.csr httpd.key
第六步:配置https
[root@Tzz ssl]# httpd -M | grep ssl #在http服务器端安装mod_ssl模块 Syntax OK ssl_module (shared) [root@Tzz conf.d]# vim ssl.conf #编辑ssl的配置文件 <VirtualHost _default_:443> #默认虚拟主机 # General setup for the virtual host, inherited from global configuration DocumentRoot "/var/www/html" #默认虚拟主机的根文档目录 ServerName www.magedu.com #https的FQDN # Server Certificate: # Point SSLCertificateFile at a PEM encoded certificate. If # the certificate is encrypted, then you will be prompted for a # pass phrase. Note that a kill -HUP will prompt again. A new # certificate can be generated using the genkey(1) command. SSLCertificateFile /etc/httpd/ssl/httpd.crt #指定证书地址 # Server Private Key: # If the key is not combined with the certificate, use this # directive to point at the key file. Keep in mind that if # you've both a RSA and a DSA private key you can configure # both in parallel (to also allow the use of DSA ciphers, etc.) SSLCertificateKeyFile /etc/httpd/ssl/httpd.key #指定密钥地址 [root@Tzz conf.d]# httpd -t Syntax OK [root@Tzz conf.d]# service httpd restart Stopping httpd: [ OK ] Starting httpd: [ OK ]
测试:
[root@localhost tmp]# openssl s_client -connect No client certificate CA names sent Server Temp Key: ECDH, prime256v1, 256 bits --- SSL handshake has read 1460 bytes and written 375 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: BE1A38B19CCE940B4080994F038488800209BA3A7F07DB9EFF12F58C155DCE2F Session-ID-ctx: Master-Key: E2A66404D25E867CDC7E54DA94B5BFFDBB77D32E6A0F317B43D89152C6638A73F5B3927821BDE4B2C883FCB26DAC07FE Key-Arg : None Krb5 Principal: None PSK identity: None PSK identity hint: None TLS session ticket lifetime hint: 300 (seconds) TLS session ticket: 0000 - 6b 98 ba 13 59 08 7a 00-db 90 49 c6 d8 2d 07 25 k...Y.z...I..-.% 0010 - 42 e0 d1 ef e0 97 c0 ce-c4 4c 07 a4 cc 74 9f 2d B........L...t.- 0020 - 8b 9c 4d 5f fb 04 7a 85-ff 23 aa 40 e6 8e a2 4c ..M_..z..#[email protected] 0030 - 1e d5 96 a2 7e 9b 49 fe-08 5c 5a 0c 33 0d df 7d ....~.I..\Z.3..} 0040 - 11 c5 ac 82 cc 87 f5 61-9f 22 4d a4 7a c1 51 07 .......a."M.z.Q. 0050 - 46 ab 5d 45 b0 18 64 13-ee 3f 12 e7 a4 0e 70 9b F.]E..d..?....p. 0060 - 03 7e b9 94 fd 82 a6 ee-e1 b3 60 e1 72 71 5a 07 .~........`.rqZ. 0070 - 61 e3 4b 73 50 88 3b 4f-0a ef 41 73 cb ce 1d ae a.KsP.;O..As.... 0080 - 3c 18 75 57 0f e6 04 74-08 60 d5 08 41 b5 ef e8 <.uW...t.`..A... 0090 - 93 6e d8 9b 9d c0 30 e9-66 fd ac 2f 83 28 01 d0 .n....0.f../.(.. 00a0 - 80 ef b1 31 85 10 dd 34-4b 25 8b 03 ae 50 d5 24 ...1...4K%...P.$ 00b0 - 57 fa 35 6e a2 62 6c 28-4b 40 85 3c 75 21 2e e9 W.5n.bl(K@.<u!.. Start Time: 1452745559 Timeout : 300 (sec) Verify return code: 21 (unable to verify the first certificate) ---
基于浏览器测试:
将自建的CA证书导出到windows下,并导入至浏览器中
18、http自带的工具程序
htpasswd:basic认证基于文件实现时,用到的账号密码文件生成工具;
apachectl:httpd自带的服务控制脚本,支持start和stop;
apxs:由httpd-devel包提供,扩展httpd使用第三方模块的工具;
rotatelogs:日志滚动工具;
access.log -->
access.log, access.1.log -->
access.log, acccess.1.log, access.2.log
suexec:访问某些有特殊权限配置的资源时,临时切换至指定用户身份运行;
ab: apache bench(压测工具)
19、httpd的压力测试工具
ab,webbench,http_load,seige
jmeter,loadrunner
tcpcopy:复制生产环境中的真是请求,并将之保存下来
ab [OPTIONS] URL
-n:总请求数;
-c:模拟的并行数;
-k:以持久连接模式 测试;
[root@Tzz ~]# ab -c10 -n1000 http://172.16.249.147/index.html This is ApacheBench, Version 2.3 <$Revision: 1430300 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 172.16.249.147 (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: Apache/2.2.15 #服务器httpd的版本 Server Hostname: 172.16.249.147 #服务器名称 Server Port: 80 #服务端口 Document Path: /index.html Document Length: 19 bytes Concurrency Level: 10 #并发级别 Time taken for tests: 0.400 seconds #请求时间 Complete requests: 1000 #完成的请求数量 Failed requests: 0 #失败的请求数量 Write errors: 0 #发送响应的失败次数 Total transferred: 309000 bytes #总共传输的字节数 HTML transferred: 19000 bytes #共传输的HTML字节数 Requests per second: 2499.15 [#/sec] (mean) #每秒完成的请求数量 Time per request: 4.001 [ms] (mean) #并发请求完成的时间 Time per request: 0.400 [ms] (mean, across all concurrent requests) #单个并发完成的时间 Transfer rate: 754.14 [Kbytes/sec] received #传输速率 Connection Times (ms) #连接时间 min mean[+/-sd] median max Connect: 0 1 0.5 1 3 #连接时间 Processing: 1 3 1.2 2 11 #请求资源时间 Waiting: 1 2 1.2 2 11 #等待时间 Total: 2 4 1.3 4 12 #总的时间 Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 4 80% 5 90% 5 95% 6 98% 7 99% 10 100% 12 (longest request)