在本地浏览器上输入www.hello.com时,简单的实现流程是:在客户端上,检查本地的hosts文件中是否有主机名和ip对应,有对应ip,则用HTTP协议封装数据请求,添加应用层首部,添加tcp首部,添加ip首部,添加mac地址后从本地出去,到对应的WEB服务器上,没有对应的ip,则查找resolv.conf文件上DNS的位置,DNS不在同一网络内,则请求需要通过网关做转发,通过路由器来寻找到对应DNS的位置,此处可能经过多个DNS解析,直到DNS找到后,将FQDN解析为一个互联网上的ip,再把请求发送到对应的WEB服务器,服务器接收到请求后,判断是否为可访问的资源,从而把资源响应给客户端。
下面通过简单的操作搭建一个LAMP平台(Linux(centos 6.6 X64)、Apache、MySQL、php组合),本次演示是通过rpm来安装的,【注意这里需要的环境是Linux可以联网,但是也可以通过光盘中rpm来进行安装,只需要注意依赖关系】后续会通过源码编译的方式搭建一个LAMP平台。
先安装httpd(也即是Apache软件基金会项目之一)
#yum install -y httpd
安装httpd的版本为httpd-2.2.15-39.el6.centos.x86_64
查看安装生成了哪些文件
# rpm -ql httpd | less 通过管道送给less,在安装文件比较多的情况,可以方便查看
常用文件介绍
配置文件有:
/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/*.conf
服务脚本:
/etc/rc.d/init.d/httpd,脚本配置文件 /etc/sysconfig/httpd
/etc/rc.d/init.d/htcacheclean把http用于使用缓存服务时使用,用于缓存清理服务脚本
模块目录:
/etc/httpd/moduels :目录下的都是链接文件
/usr/lib64/httpd/modules 实际模块文件位置
主程序:三个不能同时使用,只能使用其中一个
/usr/sbin/httpd :默认使用prefork,每个进程响应一个用户请求,预先生成多个空闲进程;
/usr/sbin/httpd.event :(httpd 2.2.X event处于测试阶段 事件驱动) 启动多个线程,每个线程响应N个请求;(httpd 2.4可用),基于事件驱动的响应方式
/usr/sbin/httpd.worker :启动多个进程,每个进程生成多个线程,每个线程响应 一个用户请求;
修改是在脚本配置文件中 /etc/sysconfig/httpd
#HTTPD=/usr/sbin/httpd.worker 取消注释,修改即可
日志文件目录:
/var/log/httpd
access_log 访问日志
error_log 错误日志
站点文档根目录:/var/www/html
如访问http://www.hello.com/oop/ki.jpg图片时 则服务器端存放位置是在/var/www/html/oop/ks.jpg
httpd的配置文件说明:配置文件分三段
# grep "Section" httpd.conf
### Section 1: Global Environment 全局配置
### Section 2: ‘Main‘ server configuration 主服务器配置
### Section 3: Virtual Hosts 虚拟主机配置
主服务器和虚拟主机不能同时使用,默认仅启用了主服务器
指令参数:不区分字符大小写,但其值有可能会区分大小写,有些指令是依赖于模块的
配置文件(/etc/httpd/conf/httpd.conf)各项说明
#
# Don‘t give away too much information about all the subcomponents
# we are running. Comment out this line if you don‘t mind remote sites
# finding out what major optional modules you are running
ServerTokens OS 指客户访问到服务器上没有的页面时,会在页面上显示服务器的版本信息等,一般不启用
如何配置此指令呢?
访问httpd文档【httpd://httpd.apache.org】,找到httpd 2.2版本的httpd,找到指令快速参考,说明如下:
ServerTokens Directive
Description: Configures the Server HTTP response header
Syntax: ServerTokens Major|Minor|Min[imal]|Prod[uctOnly]|OS|Full
Default: ServerTokens Full
Context: server config
Status: Core
Module: core
This directive controls whether Server response header field which is sent back to clients includes a description of the generic OS-type of the server as well as information about compiled-in modules.
这里是修改指令后,httpd reload访问后,显示的结果
ServerTokens Prod[uctOnly]
Server sends (e.g.): Server: Apache
ServerTokens Major
Server sends (e.g.): Server: Apache/2
ServerTokens Minor
Server sends (e.g.): Server: Apache/2.0
ServerTokens Min[imal]
Server sends (e.g.): Server: Apache/2.0.41
ServerTokens OS
Server sends (e.g.): Server: Apache/2.0.41 (Unix)
ServerTokens Full (or not specified)
Server sends (e.g.): Server: Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2
This setting applies to the entire server, and cannot be enabled or disabled on a virtualhost-by-virtualhost basis.
After version 2.0.44, this directive also controls the information presented by the ServerSignature directive.
See also
ServerSignature
ServerTokens OS 访问显示效果
ServerTokens prod访问显示效果
#
# ServerRoot: The top of the directory tree under which the server‘s
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation
# (available at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
ServerRoot "/etc/httpd" 服务器的运行目录,服务器以那个目录来运行web服务的
#
# PidFile: The file in which the server should record its process
# identification number when it starts. Note the PIDFILE variable in
# /etc/sysconfig/httpd must be set appropriately if this location is
# changed.
#
PidFile run/httpd.pid 每个服务都会有一个pid文件,这里是相对路径位置是/etc/httpd/run/httpd.pid
[[email protected] ~]# ls /etc/httpd/run/
httpd.pid httpd启动后,有此pid文件,httpd停止后,此文件被删除
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 60 接收到请求后到执行结束的时间(超时)
1、持久连接
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive Off 默认情况下,http 1.0是不支持持久连接的,此项启动后,不管http是什
么版本,都说明服务器是支持持久连接的 off 是关闭
KeepAlive {On|Off}(不一定启动就能提高服务器性能,一旦启用了持久连接,
同一个客户端在服务器上请求多个资源,中间就不用反复的3次握手4次断开,可
以提高性能,但也不是绝对的,在非常繁忙的服务器上,一个用户请求了一个资源
但是没有请求第二个,且不断开,则会白白占用连接,在非常繁忙的服务器持久连
接未必是好事,启用持久连接对绝大部分场景都是可以提高性能的,)
#
# 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
MaxKeepAliveRequests 100 在使用持久连接时,最大的请求个数
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 15
KeepAliveTimeout 15 单位是(s) 连接保持时长
2、MPM参数:
##
## Server-Pool Size Regulation (MPM specific)
##
# 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 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 没有限制每个进程可以处理的请求数
</IfModule>
pv:页面浏览计数(一个页面包含n个资源,每一个资源都要单独进行请求的,要用访问数
除以页面的资源数即是大致的一天页面浏览量)
如并发300个请求,每一个资源平均有5K大小 即每秒中使用的带宽数:
300*5K=1500KB*8=12000Kbps = 10Mbps
查看编译的模块:
[[email protected] ~]# httpd -l
Compiled in modules:
core.c 核心(httpd核心)
prefork.c
http_core.c http核心,使用到http协议时的核心功能
mod_so.c 支持模块动态加载
查看加载的模块:
[[email protected] ~]# httpd -M
httpd: Could not reliably determine the server‘s fully qualified domain name, using localhost.localdomain for ServerName
Loaded Modules:
core_module (static)
mpm_prefork_module (static)
。。。。。。。。。。。。
[[email protected] ~]# httpd.worker -l
Compiled in modules:
core.c
worker.c
http_core.c
mod_so.c
[[email protected] ~]# httpd.event -l
Compiled in modules:
core.c
event.c
http_core.c
mod_so.c
3、指定监听的地址和端口
#
# 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 [IP:]PORT 默认监听在所有地址的80端口下
此指令可重复指定多次;注意修改端口后,只有重启服务才能生效
4、DSO机制装载的模块
显示:
# httpd -D DUMP_MODULES
#
# 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.
#
# LoadModule Module_Name /path/to/Module_File
可以直接添加,服务检测到后会自动reload
#
# Load config files from the config directory "/etc/httpd/conf.d".
#
Include conf.d/*.conf 包含指定路径下的配置文件
。。。
#
# 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 以那个普通用户的身份运行此进程
### Section 2: ‘Main‘ server configuration
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. [email protected]
#
ServerAdmin [email protected] 访问不存在的页面时,返回的错误信息包含此信息(通常在代理时会显示)
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If this is not set to valid DNS name for your host, server-generated
# redirections will not work. See also the UseCanonicalName directive.
#
# If your host doesn‘t have a registered DNS name, enter its IP address here.
# You will have to access it by its address anyway, and this will make
# redirections work in a sensible way.
#
#ServerName www.example.com:80 主机名是什么,没启用会获取当前主机的主机名,不会
认可此名字,依据/etc/resolv.conf会反解为ip,如果结果不一致,则服务器是不知道自己
的名字,启动时可能会报错
[[email protected] ~]# service httpd restart
Stopping httpd: [ OK ]
Starting httpd: httpd: Could not reliably determine the server‘s fully qualified domain name, using localhost.localdomain for ServerName
[ OK ]
5、指定站点根目录
#
# 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"
DocumentRoot "/path/to/somewhere" 自己设置的话需要注意权限问题
[[email protected] ~]# cd /var/www/html/
[[email protected] html]# echo "<h1>Hello,Where come to here.</h1>" > index.html
在浏览器上输入192.168.20.163时,显示
6、站点路径访问控制
基于本地文件系统路径:
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
--------------------------------------------
/var/www/html/images/a.jpg
http://www.hello.com/images/a.jpg
--------------------------------------------
<Directory "/path/to/somewhere"> 此处/path/to/somewhere/是指/var/www/html/images/
</Directory>
基于URL访问路径做访问控制
<Location "/path/to/URL"> 此处/path/to/URL是 /images/
</Location>
7、于Directory中可用的访问控制
(1) Options 定义访问选项
Indexes: 当访问的路径下无默认的主页面,将所有资源以列表形式呈现给用
户;危险,慎用;在其前面加一个"-"是不启用此功能,不写也一样的
FollowSymlinks: 跳跃符号链接,一般不启用此功能 有此项时
[[email protected] conf.d]# ln -sv /etc/issue /var/www/html/oeo.html
`/var/www/html/oeo.html‘ -> `/etc/issue‘
在浏览器端输入http://192.168.20.163/oeo就可以访问/etc/issue文件了
(2) AllowOverride
支持在每个页面目录下创建.htaccess用于实现对此目录中资源访问时的访问控制功能。.htaccess会影响http的性能
Includes 是否允许执行服务器端包含
SymLinksifOwnerMatch 允许跟踪符号连接,如果符号链接的属主和原文件属主相同,则允许
ExecCGI 是否允许执行CGI格式的脚本页面
8、基于IP做访问控制
Order allow,deny 先允许后阻止,默认是阻止
Deny from 172.16.100.17 阻止172.16.100.17访问
Allow from 172.16.0.0/16 允许172.16.网段内的主机访问,其他主机拒绝访问
from后面能接受的地址格式:
IP, Network Address
网络地址格式较为灵活:
172.16
172.16.0.0
172.16.0.0/16
172.16.0.0/255.255.0.0
9、定义默认的主页面
#
# 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
10、配置日志功能
#
# 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 "/path/to/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 {debug|info|notice|warn|error|crit|alert|emerg} 日志级别,什么
级别与此级别以上的错误会记录
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat 定义日志格式
如:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
保留"需要使用反斜线转义
#
# For a single logfile with access, agent, and referer information
# (Combined Logfile Format), use the following directive:
#
CustomLog "/path/to/access_log" LogFormat_Name 定义访问日志存放位置
%h: 客户端地址
%l: 远程登录名,通常为-
%u: 认证时输入用户名,没有认证时为-
%t: 服务器收到 用户请求时的时间
%r:请求报文的起始行
%>s: 响应状态码
%b: 响应报文的长度,单位是字节
%{HEADER_NAME}i: 记录指定首部对应的值
192.168.20.93 - - [01/Dec/2014:08:49:45 +0800] "GET /favicon.ico HTTP/1.1" 404
289 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/40.0.2214.94 Safari/537.36 OPR/27.0.1689.66 (Edition Baidu)"
11、路径别名
站点根目录:/www/html
http://www.hello.com/images/logo/new.gif
此文件位置:/www/html/images/logo/new.gif
实现URL路径的映射,从而所访问的资源不再依赖于站点根目录;
Alias /URL/ "/path/to/somewhere/"
如: Alias /images/ "/www/images/" 注意"/"需要是一一对应的,在/www/images/中名
字不需要是相同的,
Alias /images/ "/www/hello/" 也行的,如果此时在/var/www/html/下有images,访问时
是以Alias为有效的,/var/www/html/images是无效的
http://192.168.20.163/images/ti.html ti.html是在/www/iamges目录下面的
12、设定默认字符集
ASCII
字符集:GB2312, GB18030, GBK
UTF : Unicode(国际通用码)
#
# 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 默认字符集
13、CGI脚本
CGI脚本路径别名
/var/www/cgi-bin/
http://server/cgi-bin/
bash写CGI脚本:
所有文本都使用命令输出:echo, printf, cat
执行程序:命令引用
Content-Type: text/html 指定内容信息
<pre>
</pre>
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the realname directory are treated as applications and
# run by the server when requested rather than as documents sent to the client.
# The same rules about trailing "/" apply to ScriptAlias directives as to
# Alias.
#
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" 脚本别名与Alias命令相同
/cgi-bin/下的内容通过http://server/cgi-bin/xxxx来访问
[[email protected] ~]# chmod +x /var/www/cgi-bin/bash.sh
[[email protected] ~]# cat /var/www/cgi-bin/bash.sh
#!/bin/bash
#
cat <<EOF
Content-Type: text/html
<pre>
The hostname is: $(hostname).
The datatime is: $(date)
</pre>
EOF
[[email protected] ~]# bash -n /var/www/cgi-bin/bash.sh 检查bash语法
在客户端访问:
http://192.168.20.163/cgi-bin/bash.sh
显示
The hostname is: helo.
The datatime is: Sat Mar 14 21:59:56 CST 2015
由此可以看出httpd原生就支持cgi执行的
性能提升之一:动静分离
FastCGI: 协议(通过cgi协议调用cgi服务,cgi服务主程序生成多个空闲进程,主
程序调用空闲进程来处理cgi请求,处理过后把结果返回给WEB服务器,而后此子进
程又退回到空闲进程队列中) 快速cgi模型
httpd和php交互有cgi和fastcgi、模块结合方式三种
14、基于用户访问控制 (基于ip的访问控制很容易伪装来进行访问)
用户认证:(两种方式)
基本认证: Basic 明文方式来进行发送的
摘要认证:digest 账号和密码加密后进行发送
虚拟用户:不是用于登录系统的,仅用于访问某服务或获取某资源的凭证;
用来存放用户账号和密码
文本文件:.htpasswd
SQL数据库
dbm: 基于文本文件来存放信息的数据库引擎,数据信息通过hash编码来存放,通过数据库引擎接口来交互的,提供API
ldap: 轻量级目录访问协议
authentication provider: 账号和密码的存储机制;
在httpd中简称为authn 在LoadModule中有加载对应的模块
authorization provider: 授权(访问资源与否的权限)
在httpd中简称为authz 在LoadModule中有加载对应的模块
authnz认证和授权通过同一个模块来进行的
案例:基于文件做访问控制
(1) 基于用户进行认证
<Directory "/var/www/html/admin">
Options none
AllowOverride AuthConfig 认证相关的配置
AuthType Basic
AuthName "Admin Area."
#AuthBasicProvider file(默认是使用文件)
AuthUserFile /etc/httpd/conf/.htpasswd (认证的用户)
Require valid-user (允许所有用户登录)
#Require user tom aliy (允许指定用户登录)
</Directory>
Require valid-user: 文件中所有用户均可访问
Require user USERNAME, ...
在配置文件中添加内容:
<Directory "/var/www/html/admin">
Options none
AllowOverride AuthConfig
AuthType Basic
Authname "Admin Area."
AuthUserfile /etc/httpd/conf/.htpasswd
Require valid-user
</Directory>
[[email protected] html]# ls
ovi.html
[[email protected] html]# mkdir admin
[[email protected] html]# echo "<h1>The Admin Page.</h1>" > admin/index.html
(2) 提供认证文件
htpasswd htpasswd - Manage user files for basic authentication
htpasswd is used to create and update the flat-files used to store usernames and password for basic authenti-
cation of HTTP users. If htpasswd cannot access a file, such as not being able to write to the output file or
not being able to read the file in order to update it, it returns an error status and makes no changes.
Resources available from the Apache HTTP server can be restricted to just the users listed in the files cre-
ated by htpasswd. This program can only manage usernames and passwords stored in a flat-file. It can encrypt
and display password information for use in other types of data stores, though. To use a DBM database see dbm-
manage.
-c: 如果此文件事先不存在,则创建;注意,只能在创建第一个用户时使用;
-c Create the passwdfile. If passwdfile already exists, it is rewritten and truncated. This option cannot
be combined with the -n option.
-m:以md5的格式编码存储用户的密码信息
-m Use MD5 encryption for passwords. On Windows, Netware and TPF, this is the default.
-D:删除指定用户
-D Delete user. If the username exists in the specified htpasswd file, it will be deleted.
SYNOPSIS
htpasswd [ -c ] [ -m ] [ -D ] passwdfile username
[[email protected] httpd]# htpasswd /etc/httpd/conf/.htpasswd tom
htpasswd: cannot modify file /etc/httpd/conf/.htpasswd; use ‘-c‘ to create it
[[email protected] httpd]# htpasswd -c -m /etc/httpd/conf/.htpasswd tom
New password:
Re-type new password:
Adding password for user tom
[[email protected] httpd]# htpasswd -m /etc/httpd/conf/.htpasswd aliy
New password:
Re-type new password:
Adding password for user aliy
[[email protected] httpd]# cat /etc/httpd/conf/.htpasswd
tom:$apr1$zbtyLcwE$QQgwIvBintJ./XuZtdYN70
aliy:$apr1$cT/oZ0KZ$Od9JdgbpI7tAF024yziu00
此时直接在客户端游览器输入
http://192.168.20.163/admin/
会显示
The Admin Page.
[[email protected] httpd]# service httpd reload
Reloading httpd:
再次进程访问http://192.168.20.163/admin
显示需要进程身份验证,且会有服务器提示:就是在AuthName的信息,输入用户名和密码后就能成功访问了。
再添加一个用户
[[email protected] httpd]# htpasswd -m /etc/httpd/conf/.htpasswd youke
New password:
Re-type new password:
Adding password for user youke
[[email protected] httpd]# cat /etc/httpd/conf/.htpasswd
tom:$apr1$zbtyLcwE$QQgwIvBintJ./XuZtdYN70
aliy:$apr1$cT/oZ0KZ$Od9JdgbpI7tAF024yziu00
youke:$apr1$vf26ELhE$ilKrvB28SVFrqlZl3gmgw/
访问时可以正常
到配置文件修改一下,限制只有tom、aliy可以登录
Require valid-user --> Require user tom aliy
就改变Require到如上内容
重新装载配置文件
[[email protected] httpd]# service httpd reload
Reloading httpd:
再次访问时只有tom、aliy允许访问了,youke不允许访问了
(3) 组认证
<Directory "/var/www/html/admin">
Options none
AllowOverride AuthConfig
AuthType Basic
AuthName "Admin Area."
#AuthBasicProvider file
AuthUserFile /etc/httpd/conf/.htpasswd
AuthGroupFile /etc/httpd/conf/.htgroup (手动指定组文件,在组
文件中添加用户即可)
Require group GROUP_NAME
</Directory>
组文件:
组名:user1 user2 user3
如 group1: user1 user2 user3
[[email protected] httpd]# echo "team: tom aliy" > /etc/httpd/conf/.htgroup
[[email protected] httpd]# service httpd reload
Reloading httpd:
此时只有tom、aliy可以访问,youke不能被访问
比如一些监控软件,就需要指定用户可以访问的
15、虚拟主机
虚拟主机:使用不同访问路径
基于端口
基于IP
基于主机名
http有首部的,在其中一个首部上,请求首部上有一项是host:域名(在其构建请求报文时,会在host首部上加上此次请求在浏览器中输入的域名,请求在到达目标主机之前都是基于IP地址的,根据http请求报文的首部来实现了向不同主机完成定向的)
(1) 使用虚拟主机的前提:取消主服务器
注释主服务器的站点根路径指定:DocumentRoot
### Section 3: Virtual Hosts
#
# VirtualHost: If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn‘t need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option ‘-S‘ to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
#NameVirtualHost *:80
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
#<VirtualHost *:80>
# ServerAdmin [email protected]
# DocumentRoot /www/docs/dummy-host.example.com
# ServerName dummy-host.example.com
# ErrorLog logs/dummy-host.example.com-error_log
# CustomLog logs/dummy-host.example.com-access_log common
#</VirtualHost>
(2) 定义虚拟主机
基于域名时
在httpd 2.2上必须指定NameVirtualHost IP:PORT *:80监听在所有地址上,*可以直接写ip地址
在httpd 2.4上不用指定NameVirtualHost
<VirtualHost IP:PORT> IP:PORT需要一样的
ServerName
DocumentRoot
ServerAlias
ErrorLog
CustomLog
</VirtualHost>
配置文件语法检查:
httpd -t
service httpd configtest
注意基于端口时,需要Listen指定另外的端口
基于域名时,本地修改一下hosts即可,在生产服务器端后,需要到对应的DNS服务器添加解析
测试:elinks
-dump: 获取到页面数据后直接退出进程;
基于端口的访问控制
先注释DocumentRoot,在添加一条Listen 8080监听在8080端口,后再最尾部添加如下内容
<VirtualHost *:80>
ServerName www.love.com
DocumentRoot /web/love_com
Options none
</VirtualHost>
<VirtualHost *:8080>
ServerName www.love.com
DocumentRoot /web/love_cn
</VirtualHost>
[[email protected] ~]# mkdir /web/love_{com,cn} -pv
mkdir: created directory `/web‘
mkdir: created directory `/web/love_com‘
mkdir: created directory `/web/love_cn‘
[[email protected] ~]# echo "<h1>This is love.com 80 port.</h1>" > /web/love_com/index.html
[[email protected] ~]# echo "<h1>This is love.cn 8080 port.</h1>" > /web/love_cn/index.html
[[email protected] ~]# service httpd reload
Reloading httpd:
在客户端浏览器上访问:
基于ip的访问控制
由于现在ipV4是比较紧缺,而且授权费也不低,一般比较少使用此种情况,实例如下:在配置文件中添加如下内容
<VirtualHost 192.168.20.163:80>
ServerName www.love.com
DocumentRoot /web/love_org
Options none
errorlog /var/log/httpd/love_org_error.log
Customlog /var/log/httpd/love_org_access.log combiend
</VirtualHost>
<VirtualHost 192.168.20.189:80>
ServerName www.love.com
DocumentRoot /web/love_gl
Options none
errorlog /var/log/httpd/love_gl_error.log
Customlog /var/log/httpd/love_gl_access.log combiend
</VirtualHost>
[[email protected] ~]# mkdir /web/love_{org,gl}
[[email protected] ~]# ls /web/
love_cn love_com love_gl love_org
[[email protected] ~]# ip addr add 192.168.20.189 dev eth0 添加ip
[[email protected] ~]# ip addr show dev eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:e9:e2:dc brd ff:ff:ff:ff:ff:ff
inet 192.168.20.163/24 brd 192.168.20.255 scope global eth0
inet 192.168.20.189/32 scope global eth0
inet6 fe80::20c:29ff:fee9:e2dc/64 scope link
valid_lft forever preferred_lft forever
添加主页面内容
[[email protected] ~]# echo "<h1>The IP is 192.168.20.189.</h1>" > /web/love_gl/index.html
[[email protected] ~]# echo "<h1>The IP is 192.168.20.163.</h1>" > /web/love_org/index.html
[[email protected] ~]# ping 192.168.20.189
PING 192.168.20.189 (192.168.20.189) 56(84) bytes of data.
64 bytes from 192.168.20.189: icmp_seq=1 ttl=64 time=0.222 ms
64 bytes from 192.168.20.189: icmp_seq=2 ttl=64 time=0.041 ms
^C
--- 192.168.20.189 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1571ms
rtt min/avg/max/mdev = 0.041/0.131/0.222/0.091 ms
[[email protected] ~]# service httpd reload 重新载入服务
Reloading httpd:
在客户端浏览器上访问
访问日志和错误日志都有记录
[[email protected] httpd]# pwd
/var/log/httpd
[[email protected] httpd]# ls
access_log error_log love_gl_access.log love_gl_error.log love_org_access.log love_org_error.log
基于域名的访问控制:在配置文件中添加如下内容
NameVirtualHost 192.168.20.163:80
<VirtualHost 192.168.20.163:80>
ServerName www.love.oi
DocumentRoot /web/love_oi
Options none
</VirtualHost>
<VirtualHost 192.168.20.163:80>
ServerName www.love.op
DocumentRoot /web/love_op
</VirtualHost>
[[email protected] ~]# mkdir /web/love_{oi,op}
[[email protected] ~]# ls /web/
love_cn love_com love_gl love_oi love_op love_org
[[email protected] ~]# echo "<h1>This is www.love.oi.</h1>" > /web/love_oi/index.html
[[email protected] ~]# echo "<h1>This is www.love.op.</h1>" > /web/love_op/index.html
[[email protected] ~]# vim /etc/httpd/conf/httpd.conf
[[email protected] ~]# service httpd reload
Reloading httpd:
在客户端主机上修改hosts文件,如下:
在客户端访问显示,使用ie或者是火狐(google和opera可能解析不了):
16、status页面
httpd内嵌有handler(处理器),其中有一个handler用于输出当前httpd服务相关状态信息
所用handler: server-status
启用handler要使用SetHandler指令
handler: 当文件被调用时,apache内部表示形式;一般每种文件类型都有其隐式处理器
# 基于URL访问定义
# Allow server status reports generated by mod_status,
# with the URL of http://servername/server-status
# Change the ".example.com" to match your domain to enable.
#
<Location /server-status>
SetHandler server-status
Order deny,allow
Deny from all 拒绝所有
Allow from .example.com 仅允许.example.com域内访问 此处可以做多种访问限制
#Allow from 192.168.20.0/24
--------------------------------
Order allow,deny
allow from 192.168.20.0/24
--------------------------------
</Location>
在配置文件中添加如下内容:
<Location /stus>
SetHandler server-status
Order allow,deny
Allow From 192.168.20.0/24
</Location>
修改好后
#httpd -t
#service httpd reload
测试
客户端输入 http://www.love.oi/server-status 显示服务器状态信息
17、访问属性配置总结
配置文件系统访问路径:
<Directory [~] "">
</Directory>
<File [~] ""> 对特定文件做访问控制
</File>
配置URL访问路径:
<Location [~] "">
</Location>
<LocationMatch ""> 做模式匹配和上面加 ~是一样的
</LocationMatch>
/var/www/html/
images/
18、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的常用选项:
curl - transfer a URL
-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
#curl http://192.168.20.163
#tail /var/log/httpd/access_log
可以查看到浏览器是cutl
冒充浏览器
#curl -A "IE6" http://192.168.20.197
#tail /var/log/httpd/access_log
指定从http://www.google.com.hk/test.jsp页面跳转过来
#curl -A "IE6" -e "http://www.google.com.hk/test.jsp" http://192.168.20.197
#curl -I http://www.love.oi 注意需要解析的
19、使用mod_deflate模块压缩页面优化传输速度
查看是否有mod_deflate.so 模块
测试使用chrome,输入www.love.oi,按F12,查看头部信息
Content Length:
Content-Type: 这里的格式
再复制一个大的页面文件,再访问再客户端浏览,在查看信息
SetOutputFilter DEFLATE 对输出内容符合要求的进行压缩
# mod_deflate configuration
# 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
以上配置可放在全局配置也可放在局部配置当中
到配置文件后
#httpd -t
#service httpd reload
客户端进行测试,使用chrome
强行刷新 Ctrl + F5
使用httpd -M可以看到deflate_module默认是启用的
在配置文件中添加如下内容:
SetOutputFilter DEFLATE
# mod_deflate configuration
# 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
[[email protected] ~]# httpd -t
httpd: Could not reliably determine the server‘s fully qualified domain name, using localhost.localdomain for ServerName
Syntax OK
[[email protected] ~]# service httpd reload
Reloading httpd:
[[email protected] httpd]# ls -lh /web/love_oi/index.html
-rw-r--r-- 1 root root 30 Mar 15 06:32 /web/love_oi/index.html
-rw-------. 1 root root 306K Mar 15 03:07 messages-20150315
[[email protected] httpd]# cp /var/log/messages-20150315 /web/love_oi/compress
[[email protected] httpd]# chmod +r /web/love_oi/compress
用chrome浏览器访问index.html和compress时,显示情况
这个是未添加压缩功能的显示
这个是添加压缩功能后的显示;
后续内容讲解到部署一个完整的LAMP平台,且会安装好一个discuz(论坛程序)和phpmyadmin(MySQL的管理工具)和wordpress(一个博客系统),还会提供php的加速功能和对lamp平台做压力测试。