如来神掌第一式第九招----Apache详解

###############################################################################
# Name : Mahavairocana                                                                                                                                           
# Author : Mahavairocana                                                                                                                                         
# QQ : 10353512                                                                                                                                                    
# WeChat : shenlan-qianlan                                                                                                                                      
# Blog : http://www.cnblogs.com/Mahavairocana/                                                                                                       
# Description : You are welcome to reprint, or hyperlinks to indicate the                                                                        
#                    source of the article, as well as author information.                                                                                ###############################################################################

一、一次完整的http请求过程
1、建立或者处理链接,接受请求或者拒绝请求;
2、接收请求;接收来自网络的请求报文中对某资源的一次请求过程;
    并发响应模型,
        单线程I/O结构;串行,启动一个进程处理用户请求,而且一次只处理一个;
        多线程I/O结构;并行,启动多个进程,每个进程处理一个请求;(不建议启动太多进程)
        复用I/O结构:    一个进程相遇多个用户请求;
            多线程模型:一个进程生成N个线程,每个线程相应一个用户请求;
            事件驱动:    event-drlven
        复用的多进程I/0结构:启动多个(m)进程,每个进程响应m个请求;
        
3、处理请求:对请求报文进行解析,并获取请求的资源及请求方法等信息相关信息
    元数据:请求报文首部
        <method>
        Host: console2.ctyun.cn    请求的主机名
        Connection:
        <>

4、访问资源:获取(从硬盘中)请求报文中请求的资源
    

5、构建响应报文
    MIME 类型:
    
    魔法分类:服务器对资源内容进行扫描,将其与一个已知模式表进行匹配,以决定文件的MIME类型
    显式分类:强制特定文件或目录内容拥有某个MIME类型
    类型协商:与用户协商来决定使用哪种类型
    
    ULR重定向:
        WEB服务构建的相应并非客户端请求的资源,而是资源另外一个访问路径;
        永久删除的资源 资源可能已经被移动到新的位置,或者被重命名,有了一个新的URL,Web服务器这时会告诉客户端资源被修改,客户端会更新书签/地址去用新的URL获取资源,状态码301 Moved Permanently。

        临时删除的资源 如果资源只是临时被移动或者修改,后续还是会修改回原状时,Web服务器需要客户端不要用新的地址/书签获取资源,状态码303 See Other 及 307 Temporary Redirect。
        URL增强  当请求到达时服务器会生成一个新的包含了嵌入式状态信息的URL,并将用户重定向到这个新的URL上去。客户端会根据这个新URL重新发起请求,这次的请求会包含完整的、经过状态增强的URL。
        负载均衡  如果负载过重的服务器收到请求,可以将其定向到一个负载不太重的服务器上去,状态码303,307。
        服务器关联  服务器可能含有其他用户的本地信息,服务端可以将客户端重定向到包含那个客户端信息的服务器上去,状态码303,307。
        规范目录名称  客户端请求的URI是个不带尾部斜线的目录名时,大部分服务器都会将客户端定向到一个加了斜线的URI上去,这样链接就可以正常工作了。
        
        
6、发送响应报文
    持久连接:服务器在发出响应后保持TCP连接继续打开着。同一客户/服务器之间的后续请求和响应可以通过这个连接传递。
    
    非持久连接:服务器发送一个对象后相关的TCP连接就被关闭
        缺点(一)客户得为每个待请求的对象建立并维护一个新得连接。对于每个这个的连接,TCP必须同时在客户端和服务器端分配TCP缓冲区,并维护TCP变量。对于有可能同时为来自数百个不同客户的请求提供服务的Web服务器来说,这会严重增加服务器的负担;
        缺点(二)对每个对象请求都有2个RTT的响应延迟:一个RTT用于建立TCP连接,另一个RTT用于请求和接收对象;
        缺点(三)每个对象都要经历 TCP 缓启动,因为每个TCP连接都要起始于slow start 阶段。并行TCP连接的使用能够部分减轻RTT延迟和缓启动的影响。

7、记录日志,做用户行为分析;

二、HTTP协议基础知识

URL 统一资源定位符.  作用:标明了互联网上资源的地址。通俗的说它就是个地址。

相对地址:相对于某个地址的地址   eg:你们家门口的苏果超市
绝对地址:纯地址  eg:地球/中国/xx/xx/xxx/xx路/苏果超市。

SSL会话的简化过程
(1) 客户端发送可供选择的加密方式,并向服务器请求证书;
(2) 服务器端发送证书以及选定的加密方式给客户端;
(3) 客户端取得证书并进行证书验正:
    如果信任给其发证书的CA:
        (a) 验正证书来源的合法性;用CA的公钥解密证书上数字签名;
        (b) 验正证书的内容的合法性:完整性验正
        (c) 检查证书的有效期限;
        (d) 检查证书是否被吊销;
        (e) 证书中拥有者的名字,与访问的目标主机要一致;
(4) 客户端生成临时会话密钥(对称密钥),并使用服务器端的公钥加密此数据发送给服务器,完成密钥交换;
(5) 服务用此密钥加密用户请求的资源,响应给客户端;
SSL会话是基于IP地址创建;所以单IP的主机上,仅可以使用一个https虚拟主机;

三、Apache 特性

httpd 特性
    高度模块化: core + modules
            DSO:dynamic shared object
            MPM:Multipath processing Modules (多路处理模块)
                prefork:多进程模型,每个进程响应一个请求;
                    一个主进程:负责生成子进程及回收子进程;负责创建套接字;负责接收请求,并将其派发给某子进程进行处理;
                    n个子进程:每个子进程处理一个请求;
                    工作模型:会预先生成几个空闲进程,随时等待用于响应用户请求;最大空闲和最小空闲;
                worker:多进程多线程模型,每线程处理一个用户请求;
                    一个主进程:负责生成子进程;负责创建套接字;负责接收请求,并将其派发给某子进程进行处理;
                    多个子进程:每个子进程负责生成多个线程;
                    每个线程:负责响应用户请求;
                    并发响应数量:m*n
                        m:子进程数量
                        n:每个子进程所能创建的最大线程数量;
                event:事件驱动模型,多进程模型,每个进程响应多个请求;
                    一个主进程 :负责生成子进程;负责创建套接字;负责接收请求,并将其派发给某子进程进行处理;
httpd-2.4:依赖于apr-1.4+, apr-util-1.4+, [apr-iconv]
        
        新特性:
            (1) MPM支持运行为DSO机制;以模块形式按需加载;
            (2) event MPM生产环境可用;
            (3) 异步读写机制;
            (4) 支持每模块及每目录的单独日志级别定义;
            (5) 每请求相关的专用配置;
            (6) 增强版的表达式分析式;
            (7) 毫秒级持久连接时长定义;
            (8) 基于FQDN的虚拟主机也不再需要NameVirutalHost指令;
            (9) 新指令,AllowOverrideList;
            (10) 支持用户自定义变量;
            (11) 更低的内存消耗;
            
        新模块:
            (1) mod_proxy_fcgi
            (2) mod_proxy_scgi
            (3) mod_remoteip

编译安装

  

编译安装步骤:
(1) apr-1.4+
    # ./configure  --prefix=/usr/local/apr
    # make && make install
    
(2) apr-util-1.4+
    # ./configure  --prefix=/usr/local/apr-util  --with-apr=/usr/local/apr
    # make && make install
    
(3) httpd-2.4
    # ./configure --prefix=/usr/local/apache24 --sysconfdir=/etc/httpd24  --enable-so --enable-ssl --enable-cgi --enable-rewrite --with-zlib --with-pcre --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr-util --enable-modules=most --enable-mpms-shared=all --with-mpm=prefork
    # make  && make install
    
    自带的服务控制脚本:apachectl

三、配置详解

  1、主配置文件

#
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# The configuration directives are grouped into three basic sections:
#  1. Directives that control the operation of the Apache server process as a
#     whole (the 'global environment').
#  2. Directives that define the parameters of the 'main' or 'default' server,
#     which responds to requests that aren't handled by a virtual host.
#     These directives also provide default values for the settings
#     of all virtual hosts.
#  3. Settings for virtual hosts, which allow Web requests to be sent to
#     different IP addresses or hostnames and have them handled by the
#     same Apache server process.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo.log"
# with ServerRoot set to "/etc/httpd" will be interpreted by the
# server as "/etc/httpd/logs/foo.log".
#

### Section 1: Global Environment   #-全局环境配置,决定Apache服务器的全局参数
#
# The directives in this section affect the overall operation of Apache,
# such as the number of concurrent requests it can handle or where it
# can find its configuration files.
#

#
# 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

#
# 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"

#
# 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

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 60

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive Off        #是否开启持久连接

#
# 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      ##数量限制

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 15                ##时间限制

##
## 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     #最大空闲线程数,配置有问题,按照该配置服务默认启动的时候会被kill掉一个线程
ThreadsPerChild     25    #每个进程所能启动的线程数量
MaxRequestsPerChild  0    #每个线程所能响应的最大请求数量,0表示不做限制
</IfModule>

#
# 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

#
# 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
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule info_module modules/mod_info.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule cache_module modules/mod_cache.so
LoadModule suexec_module modules/mod_suexec.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule version_module modules/mod_version.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
#

#
# Load config files from the config directory "/etc/httpd/conf.d".
#
Include conf.d/*.conf

#
# ExtendedStatus controls whether Apache will generate "full" status
# information (ExtendedStatus On) or just basic information (ExtendedStatus
# Off) when the "server-status" handler is called. The default is Off.
#
ExtendedStatus On  #显示更详细的扩展状态信息,配合service-status用,960行

#
# 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  #主服务配置,相当于是Apache中的默认Web站点,如果我们的服务器中只有一个站点,那么就只需在这里配置就可以了。
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# 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. admin@your-domain.com
#
ServerAdmin root@localhost

#
# 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

#
# UseCanonicalName: Determines how Apache constructs self-referencing 
# URLs and the SERVER_NAME and SERVER_PORT variables.
# When set "Off", Apache will use the Hostname and Port supplied
# by the client.  When set "On", Apache will use the value of the
# ServerName directive.
#
UseCanonicalName Off

#
# 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路径的起始位置;

#
# 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.  
#
<Directory />    ##站点访问控制,可以基于两种类型的路径指明对哪些资源进行访问控制
    Options FollowSymLinks
    AllowOverride None
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# This should be changed to whatever you set DocumentRoot to.
#
<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   #支持多个选项  Indexes Includes FollowSymLinks Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews ExecCGI MultiViews  None
        Indexes:索引,无指引的时候,找默认主页如index.html,如果没有默认指引,则把路径下所有页面都列出来; (没有索引文件,但是开启索引非常危险,用户可以下载到整站源码,除了下载业务,不建议开启该功能)
        FollowSymLinks:允许跟踪服务连接文件
        None:拒绝所哟
        SymLinksifOwnerMatch:符号连接用户于文件用户相同即可查看
        ExecCGI:是否允许执行CGI脚本 
        
#
# 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
        #None  表示禁止用户对目录配置文件(.htaccess进行修改)重载,不建议开启

#
# Controls who can get stuff from this server.
#
#基于来源地址访问机制

    Order allow,deny    ##白名单,默认拒绝所有;
    Allow from all        ##配合白名单工作;

    Order deny,allow    ##黑名单,
    Allow from all        ##配合黑名单工作;
    
    基于IP地址限制,将all 替换为网段信息
        172.16   172.16.0.0  172.16.0.0/16   172.16.0.0/255.255.252.0
    基于FQDN限制 
    
    
    
</Directory>

#
# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received.
#
# The path to the end user account 'public_html' directory must be
# accessible to the webserver userid.  This usually means that ~userid
# must have permissions of 711, ~userid/public_html must have permissions
# of 755, and documents contained therein must be world-readable.
# Otherwise, the client will only receive a "403 Forbidden" message.
#
# See also: http://httpd.apache.org/docs/misc/FAQ.html#forbidden
#
<IfModule mod_userdir.c>
    #
    # UserDir is disabled by default since it can confirm the presence
    # of a username on the system (depending on home directory
    # permissions).
    #
    UserDir disabled

    #
    # To enable requests to /~user/ to serve the user's public_html
    # directory, remove the "UserDir disabled" line above, and uncomment
    # the following line instead:
    # 
    #UserDir public_html

</IfModule>

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /home/*/public_html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

#
# 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    #默认访问页面

#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

#
# TypesConfig describes where the mime.types file (or equivalent) is
# to be found.
#
TypesConfig /etc/mime.types

#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain

#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type.  The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
<IfModule mod_mime_magic.c>
#   MIMEMagicFile /usr/share/magic.mime
    MIMEMagicFile conf/magic
</IfModule>

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

#
# EnableMMAP: Control whether memory-mapping is used to deliver
# files (assuming that the underlying OS supports it).
# The default is on; turn this off if you serve from NFS-mounted 
# filesystems.  On some systems, turning it off (regardless of
# filesystem) can improve performance; for details, please see
# http://httpd.apache.org/docs/2.2/mod/core.html#enablemmap
#
#EnableMMAP off

#
# EnableSendfile: Control whether the sendfile kernel support is 
# used to deliver files (assuming that the OS supports it). 
# The default is on; turn this off if you serve from NFS-mounted 
# filesystems.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#enablesendfile
#
#EnableSendfile off

#
# 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    #错误日志级别 可定义为debug, info, notice, warn, error, crit,alert, emerg.

#
# 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
    #%h:客户端IP地址;
    #%l:Remote User, 通常为一个减号(“-”);
    #%u:Remote user (from auth; may be bogus if return status (%s) is 401);非为登录访问时,其为一个减号;
    #%t:服务器收到请求时的时间;
    #%r:First line of request,即表示请求报文的首行;记录了此次请求的“方法”,“URL”以及协议版本;
    #%>s:响应状态码;
    #%b:响应报文的大小,单位是字节;不包括响应报文的http首部;
    #%{Referer}i:请求报文中首部“referer”的值;即从哪个页面中的超链接跳转至当前页面的;
    #%{User-Agent}i:请求报文中首部“User-Agent”的值;即发出请求的应用程序;
    #x-forwarded-for:通过LB后,获取客户端真实IP地址
    
# "combinedio" includes actual counts of actual bytes received (%I) and sent (%O); this
# requires the mod_logio module to be loaded.
#LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %I %O" combinedio
#LogFormat "%{x-forwarded-for}i %l %u %t "%r" %>s %b "%{Referer}i" "%{Cookie}i" "%{User-Agent}i" "%{Content-Length}i""

#
# 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

#
# If you would like to have separate agent and referer logfiles, uncomment
# the following directives.
#
#CustomLog logs/referer_log referer
#CustomLog logs/agent_log agent

#
# For a single logfile with access, agent, and referer information
# (Combined Logfile Format), use the following directive:
#
CustomLog logs/access_log combined  # 日志文件在access_log   combined为日志格式,可以配置combined common  agent ;

#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
#
ServerSignature On

#
# Aliases: Add here as many aliases as you need (with no limit). The format is 
# Alias fakename realname
#
# Note that if you include a trailing / on fakename then the server will
# require it to be present in the URL.  So "/icons" isn't aliased in this
# example, only "/icons/".  If the fakename is slash-terminated, then the 
# realname must also be slash terminated, and if the fakename omits the 
# trailing slash, the realname must also omit it.
#
# We include the /icons/ alias for FancyIndexed directory listings.  If you
# do not use FancyIndexing, you may comment this out.
#
Alias /icons/ "/var/www/icons/"            ###做别名

<Directory "/var/www/icons">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

<Directory "/www/htdocs/console2">
    Options None
    AllowOverride None
    AuthType    Basic
    AuthNmae    "Admin"#认证提示
    AuthUserFile    "/etc/httpd/conf/.httpassed" ## 使用htpasswd 生成
    AuthGroupFile    "/etc/httpd/conf/.httgroup"     ##格式  groupa:1 2 以空格隔开
    Require group groupa    #只允许groupa用户访问
</Directory>


#
# WebDAV module configuration section.
# 
<IfModule mod_dav_fs.c>
    # Location of the WebDAV lock database.
    DAVLockDB /var/lib/dav/lockdb
</IfModule>

#
# 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/"

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

#
# Redirect allows you to tell clients about documents which used to exist in
# your server's namespace, but do not anymore. This allows you to tell the
# clients where to look for the relocated document.
# Example:
# Redirect permanent /foo http://www.example.com/bar

#
# Directives controlling the display of server-generated directory listings.
#

#
# IndexOptions: Controls the appearance of server-generated directory
# listings.
#
IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable Charset=UTF-8

#
# AddIcon* directives tell the server which icon to show for different
# files or filename extensions.  These are only displayed for
# FancyIndexed directories.
#
AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip

AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*

AddIcon /icons/binary.gif .bin .exe
AddIcon /icons/binhex.gif .hqx
AddIcon /icons/tar.gif .tar
AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
AddIcon /icons/a.gif .ps .ai .eps
AddIcon /icons/layout.gif .html .shtml .htm .pdf
AddIcon /icons/text.gif .txt
AddIcon /icons/c.gif .c
AddIcon /icons/p.gif .pl .py
AddIcon /icons/f.gif .for
AddIcon /icons/dvi.gif .dvi
AddIcon /icons/uuencoded.gif .uu
AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
AddIcon /icons/tex.gif .tex
AddIcon /icons/bomb.gif /core

AddIcon /icons/back.gif ..
AddIcon /icons/hand.right.gif README
AddIcon /icons/folder.gif ^^DIRECTORY^^
AddIcon /icons/blank.gif ^^BLANKICON^^

#
# DefaultIcon is which icon to show for files which do not have an icon
# explicitly set.
#
DefaultIcon /icons/unknown.gif

#
# AddDescription allows you to place a short description after a file in
# server-generated indexes.  These are only displayed for FancyIndexed
# directories.
# Format: AddDescription "description" filename
#
#AddDescription "GZIP compressed document" .gz
#AddDescription "tar archive" .tar
#AddDescription "GZIP compressed tar archive" .tgz

#
# ReadmeName is the name of the README file the server will look for by
# default, and append to directory listings.
#
# HeaderName is the name of a file which should be prepended to
# directory indexes. 
ReadmeName README.html
HeaderName HEADER.html

#
# IndexIgnore is a set of filenames which directory indexing should ignore
# and not include in the listing.  Shell-style wildcarding is permitted.
#
IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t

#
# DefaultLanguage and AddLanguage allows you to specify the language of 
# a document. You can then use content negotiation to give a browser a 
# file in a language the user can understand.
#
# Specify a default language. This means that all data
# going out without a specific language tag (see below) will 
# be marked with this one. You probably do NOT want to set
# this unless you are sure it is correct for all cases.
#
# * It is generally better to not mark a page as 
# * being a certain language than marking it with the wrong
# * language!
#
# DefaultLanguage nl
#
# Note 1: The suffix does not have to be the same as the language
# keyword --- those with documents in Polish (whose net-standard
# language code is pl) may wish to use "AddLanguage pl .po" to
# avoid the ambiguity with the common suffix for perl scripts.
#
# Note 2: The example entries below illustrate that in some cases 
# the two character 'Language' abbreviation is not identical to 
# the two character 'Country' code for its country,
# E.g. 'Danmark/dk' versus 'Danish/da'.
#
# Note 3: In the case of 'ltz' we violate the RFC by using a three char
# specifier. There is 'work in progress' to fix this and get
# the reference data for rfc1766 cleaned up.
#
# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl)
# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de)
# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja)
# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn)
# Norwegian (no) - Polish (pl) - Portugese (pt)
# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv)
# Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW)
#
AddLanguage ca .ca
AddLanguage cs .cz .cs
AddLanguage da .dk
AddLanguage de .de
AddLanguage el .el
AddLanguage en .en
AddLanguage eo .eo
AddLanguage es .es
AddLanguage et .et
AddLanguage fr .fr
AddLanguage he .he
AddLanguage hr .hr
AddLanguage it .it
AddLanguage ja .ja
AddLanguage ko .ko
AddLanguage ltz .ltz
AddLanguage nl .nl
AddLanguage nn .nn
AddLanguage no .no
AddLanguage pl .po
AddLanguage pt .pt
AddLanguage pt-BR .pt-br
AddLanguage ru .ru
AddLanguage sv .sv
AddLanguage zh-CN .zh-cn
AddLanguage zh-TW .zh-tw

#
# LanguagePriority allows you to give precedence to some languages
# in case of a tie during content negotiation.
#
# Just list the languages in decreasing order of preference. We have
# more or less alphabetized them here. You probably want to change this.
#
LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW

#
# ForceLanguagePriority allows you to serve a result page rather than
# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback)
# [in case no accepted languages matched the available variants]
#
ForceLanguagePriority Prefer Fallback

#
# 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  设置字符集  GB2312 ……

#
# AddType allows you to add to or override the MIME configuration
# file mime.types for specific file types.
#
#AddType application/x-tar .tgz

#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
# Despite the name similarity, the following Add* directives have nothing
# to do with the FancyIndexing customization directives above.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz

# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz

#
#   MIME-types for downloading Certificates and CRLs
#
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl

#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi

#
# For files that include their own HTTP headers:
#
#AddHandler send-as-is asis

#
# For type maps (negotiated resources):
# (This is enabled by default to allow the Apache "It Worked" page
#  to be distributed in multiple languages.)
#
AddHandler type-map var

#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml

#
# Action lets you define media types that will execute a script whenever
# a matching file is called. This eliminates the need for repeated URL
# pathnames for oft-used CGI file processors.
# Format: Action media/type /cgi-script/location
# Format: Action handler-name /cgi-script/location
#

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# Putting this all together, we can internationalize error responses.
#
# We use Alias to redirect any /error/HTTP_<error>.html.var response to
# our collection of by-error message multi-language collections.  We use 
# includes to substitute the appropriate text.
#
# You can modify the messages' appearance without changing any of the
# default HTTP_<error>.html.var files by adding the line:
#
#   Alias /error/include/ "/your/include/path/"
#
# which allows you to create your own set of files by starting with the
# /var/www/error/include/ files and
# copying them to /your/include/path/, even on a per-VirtualHost basis.
#

Alias /error/ "/var/www/error/"

<IfModule mod_negotiation.c>
<IfModule mod_include.c>
    <Directory "/var/www/error">
        AllowOverride None
        Options IncludesNoExec
        AddOutputFilter Includes html
        AddHandler type-map var
        Order allow,deny
        Allow from all
        LanguagePriority en es de fr
        ForceLanguagePriority Prefer Fallback
    </Directory>

#    ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
#    ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
#    ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
#    ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
#    ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
#    ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
#    ErrorDocument 410 /error/HTTP_GONE.html.var
#    ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
#    ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
#    ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
#    ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
#    ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var
#    ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
#    ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
#    ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
#    ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
#    ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var

</IfModule>
</IfModule>

#
# The following directives modify normal HTTP response behavior to
# handle known problems with browser implementations.
#
BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch "MSIE 4.0b2;" nokeepalive downgrade-1.0 force-response-1.0
BrowserMatch "RealPlayer 4.0" force-response-1.0
BrowserMatch "Java/1.0" force-response-1.0
BrowserMatch "JDK/1.0" force-response-1.0

#
# The following directive disables redirects on non-GET requests for
# a directory that does not include the trailing slash.  This fixes a 
# problem with Microsoft WebFolders which does not appropriately handle 
# redirects for folders with DAV methods.
# Same deal with Apple's DAV filesystem and Gnome VFS support for DAV.
#
BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
BrowserMatch "MS FrontPage" redirect-carefully
BrowserMatch "^WebDrive" redirect-carefully
BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
BrowserMatch "^gnome-vfs/1.0" redirect-carefully
BrowserMatch "^XML Spy" redirect-carefully
BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully

#
# 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 all
    Allow from .example.com
</Location>

#
# Allow remote server configuration reports, with the URL of
#  http://servername/server-info (requires that mod_info.c be loaded).
# Change the ".example.com" to match your domain to enable.
#
#<Location /server-info>
#    SetHandler server-info
#    Order deny,allow
#    Deny from all
#    Allow from .example.com
#</Location>

#
# Proxy Server directives. Uncomment the following lines to
# enable the proxy server:
#
#<IfModule mod_proxy.c>
#ProxyRequests On
#
#<Proxy *>
#    Order deny,allow
#    Deny from all
#    Allow from .example.com
#</Proxy>

#
# Enable/disable the handling of HTTP/1.1 "Via:" headers.
# ("Full" adds the server version; "Block" removes all outgoing Via: headers)
# Set to one of: Off | On | Full | Block
#
#ProxyVia On

#
# To enable a cache of proxied content, uncomment the following lines.
# See http://httpd.apache.org/docs/2.2/mod/mod_cache.html for more details.
#
#<IfModule mod_disk_cache.c>
#   CacheEnable disk /
#   CacheRoot "/var/cache/mod_proxy"
#</IfModule>
#

#</IfModule>
# End of proxy directives.



### Section 3: Virtual Hosts  #虚拟主机,虚拟主机不能与Main Server主服务器共存,当启用了虚拟主机之后,Main Server就不能使用了
#
# 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 webmaster@dummy-host.example.com
#    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>


SetOutputFilter DEFLATE            #开启压缩,依赖deflate_module modules模块。 可以查看Content-Encoding 为GZIP

# 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 MSI[E]  !no-gzip !gzip-only-text/html


虚拟主机
            
站点标识: socket
    IP相同,但端口不同;
    IP不同,但端口均为默认端口;
    FQDN不同;
        请求报文中首部
        Host: www.magedu.com 
        
有三种实现方案:
    基于ip:
        为每个虚拟主机准备至少一个ip地址;
    基于port:
        为每个虚拟主机使用至少一个独立的port;
    基于FQDN:
        为每个虚拟主机使用至少一个FQDN;

注意:一般虚拟机不要与中心主机混用;因此,要使用虚拟主机,得先禁用'main'主机;
    禁用方法:注释中心主机的DocumentRoot指令即可;
    
虚拟主机的配置方法:
    <VirtualHost  IP:PORT>
        ServerName FQDN
        DocumentRoot  ""
    </VirtualHost>
    
    其它可用指令:
        ServerAlias:虚拟主机的别名;可多次使用;
        ErrorLog:
        CustomLog:
        <Directory "">
        ...
        </Directory>
        Alias
        ...
        
    基于IP的虚拟主机示例:
    <VirtualHost 172.16.100.6:80>
        ServerName www.a.com
        DocumentRoot "/www/a.com/htdocs"
    </VirtualHost>

    <VirtualHost 172.16.100.7:80>
        ServerName www.b.net
        DocumentRoot "/www/b.net/htdocs"
    </VirtualHost>

    <VirtualHost 172.16.100.8:80>
        ServerName www.c.org
        DocumentRoot "/www/c.org/htdocs"
    </VirtualHost>
    
    基于端口的虚拟主机:
    <VirtualHost 172.16.100.6:80>
        ServerName www.a.com
        DocumentRoot "/www/a.com/htdocs"
    </VirtualHost>

    <VirtualHost 172.16.100.6:808>
        ServerName www.b.net
        DocumentRoot "/www/b.net/htdocs"
    </VirtualHost>

    <VirtualHost 172.16.100.6:8080>
        ServerName www.c.org
        DocumentRoot "/www/c.org/htdocs"
    </VirtualHost>
    
    基于FQDN的虚拟主机:
    NameVirtualHost 172.16.100.6:80

    <VirtualHost 172.16.100.6:80>
        ServerName www.a.com
        DocumentRoot "/www/a.com/htdocs"
    </VirtualHost>

    <VirtualHost 172.16.100.6:80>
        ServerName www.b.net
        DocumentRoot "/www/b.net/htdocs"
    </VirtualHost>

    <VirtualHost 172.16.100.6:80>
        ServerName www.c.org
        DocumentRoot "/www/c.org/htdocs"
    </VirtualHost>        

  2、配置https ssl配置文件

  

#
# This is the Apache server configuration file providing SSL support.
# It contains the configuration directives to instruct the server how to
# serve pages over an https connection. For detailing information about these 
# directives see <URL:http://httpd.apache.org/docs/2.2/mod/mod_ssl.html>
# 
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#

LoadModule ssl_module modules/mod_ssl.so

#
# When we also provide SSL we have to listen to the 
# the HTTPS port in addition.
#
Listen 443

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is a internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog  builtin

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism 
#   to use and second the expiring timeout (in seconds).
SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300

#   Semaphore:
#   Configure the path to the mutual exclusion semaphore the
#   SSL engine uses internally for inter-process synchronization. 
SSLMutex default

#   Pseudo Random Number Generator (PRNG):
#   Configure one or more sources to seed the PRNG of the 
#   SSL library. The seed data should be of good random quality.
#   WARNING! On some platforms /dev/random blocks if not enough entropy
#   is available. This means you then cannot use the /dev/random device
#   because it would lead to very long connection times (as long as
#   it requires to make more entropy available). But usually those
#   platforms additionally provide a /dev/urandom device which doesn't
#   block. So, if available, use this one instead. Read the mod_ssl User
#   Manual for more details.
SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin
#SSLRandomSeed startup file:/dev/random  512
#SSLRandomSeed connect file:/dev/random  512
#SSLRandomSeed connect file:/dev/urandom 512

#
# Use "SSLCryptoDevice" to enable any supported hardware
# accelerators. Use "openssl engine -v" to list supported
# engine names.  NOTE: If you enable an accelerator and the
# server does not start, consult the error logs and ensure
# your accelerator is functioning properly. 
#
SSLCryptoDevice builtin
#SSLCryptoDevice ubsec

##
## SSL Virtual Host Context
##

<VirtualHost _default_:443>

# General setup for the virtual host, inherited from global configuration
DocumentRoot "/var/www/html"
ServerName www.example.com:443

# Use separate log files for the SSL virtual host; note that LogLevel
# is not inherited from httpd.conf.
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on    #

#   SSL Protocol support:
# List the enable protocol levels with which clients will be able to
# connect.  Disable SSLv2 access by default:
SSLProtocol all -SSLv2    #支持哪些协议, -SSLv2表示不支持V2

#   SSL Cipher Suite:
# List the ciphers that the client is permitted to negotiate.
# See the mod_ssl documentation for a complete list.
SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES  #支持哪些加密套件 !不支持 + 表示额外支持

#   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/pki/tls/certs/localhost.crt    #用于客户端验证的文件,指明到真实配置文件目录下;

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convinience.
#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require    #是否验证客户端证书,默认关闭,大多客户端无证书
#SSLVerifyDepth  10

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ 
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." 
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} 
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) 
#           or %{REMOTE_ADDR} =~ m/^192.76.162.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context. 
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<Files ~ ".(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is send or allowed to received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is send and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly. 
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
SetEnvIf User-Agent ".*MSIE.*" 
         nokeepalive ssl-unclean-shutdown 
         downgrade-1.0 force-response-1.0

#   Per-Server Logging:
#   The home of a custom SSL log file. Use this when you want a
#   compact non-error SSL logfile on a virtual host basis.
CustomLog logs/ssl_request_log 
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x "%r" %b"

</VirtualHost>                                  

  3、常用辅助配置文件一

  

[root@Mahavairocana ~]# cat /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.
#修改MPM运行方式
#HTTPD=/usr/sbin/httpd.worker
#HTTPD=/usr/sbin/httpd.event

#
# To pass additional options (for instance, -D definitions) to the
# httpd binary at startup, set OPTIONS here.
#
#OPTIONS=

#
# By default, the httpd process is started in the C locale; to 
# change the locale in which the server runs, the HTTPD_LANG
# variable can be set.
#
#HTTPD_LANG=C

#
# By default, the httpd process will create the file
# /var/run/httpd/httpd.pid in which it records its process
# identification number when it starts.  If an alternate location is
# specified in httpd.conf (via the PidFile directive), the new
# location needs to be reported in the PIDFILE.
#
#PIDFILE=/var/run/httpd/httpd.pid

 四、创建证书

创建私有CA: 
进入/etc/pki/CA
(umask 077;openssl genrsa -out private/cakey.pem 2048)
touch index.txt
echo 01 > serial
[root@Mahavairocana CA]# openssl req -new -x509 -key private/cakey.pem  -out cacert.pem -days 365
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]:Ctyun.cn
Organizational Unit Name (eg, section) []:Ops
Common Name (eg, your name or your server's hostname) []:ca.ctyun.com
Email Address []:mail.ctyun.com


创建http 证书
[root@Mahavairocana httpd]# openssl req -new -key httpd.key -out httpd.csr
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]:CTYUN
Organizational Unit Name (eg, section) []:CTYUN
Common Name (eg, your name or your server's hostname) []:console2.ctyun.cn
Email Address []:mail.ctyun.cn

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:1
string is too short, it needs to be at least 4 bytes long
A challenge password []:2018.com.CN
An optional company name []:bIAU


[root@Mahavairocana httpd]# openssl ca -in httpd.csr -out /etc/pki/CA/certs/console2.ctyun.cn.crt -days 72000
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
The stateOrProvinceName field needed to be the same in the
CA certificate (Beijing) and the request (beijing)

[root@Mahavairocana httpd]# mv httpd.* ssl/
[root@Mahavairocana httpd]# cp /etc/pki/CA/certs/console2.ctyun.cn.crt  ./ssl/

安装ssl模块;
yum -y install mod_ssl

五、使用小技巧:

1、启动报错   “Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName”

Starting httpd: httpd: apr_sockaddr_info_get() failed for Mahavairocana
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
   
解决方法: [ OK ] 增加 ServerName localhost:80

2、查看目前运行MPM模块

[root@Mahavairocana ~]# ps -ef | grep httpd  查看,默认是 prefork 即httpd;
root      24162      1  0 00:11 ?        00:00:00 /usr/sbin/httpd.worker
apache    24164  24162  0 00:11 ?        00:00:00 /usr/sbin/httpd.worker
apache    24166  24162  0 00:11 ?        00:00:00 /usr/sbin/httpd.worker
apache    24170  24162  0 00:11 ?        00:00:00 /usr/sbin/httpd.worker

[root@Mahavairocana ~]# cat /etc/sysconfig/httpd 查看使用模块 #HTTPD=/usr/sbin/httpd.worker HTTPD=/usr/sbin/httpd.event

3、为何允许MPM允许在worker是,进程先启动4个,随后又kill掉一个(参考配置详解中主配置文件worker相关配置)

[root@Mahavairocana ~]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]
[root@Mahavairocana ~]# ps -ef | grep httpd  
root      25178      1  2 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25179  25178  0 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25180  25178  1 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25181  25178  0 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25264  25178  3 00:34 ?        00:00:00 /usr/sbin/httpd.worker
root      25293  23653  0 00:34 pts/0    00:00:00 grep httpd
[root@Mahavairocana ~]# ps -ef | grep httpd  
root      25178      1  0 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25179  25178  0 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25181  25178  0 00:34 ?        00:00:00 /usr/sbin/httpd.worker
apache    25264  25178  0 00:34 ?        00:00:00 /usr/sbin/httpd.worker
root      25295  23653  0 00:34 pts/0    00:00:00 grep httpd

4、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服务器等等,功能十分强大。
            
            MIME: major/minor,  image/png, image/gif

            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    

            用法:curl [options] [URL...]

            另一个工具:elinks
                elinks  [OPTION]... [URL]...
                    -dump: 不进入交互式模式,而直接将URL的内容输出至标准输出; 

 5、httpd的压力测试工具

ab, webbench, http_load, seige

jmeter, loadrunner

tcpcopy:网易,复制生产环境中的真实请求,并将之保存下来;

ab  [OPTIONS]  URL
    -n:总请求数;
    -c:模拟的并行数;
    -k:以持久连接模式 测试;

eg:
[root@Mahavairocana ~]# ab -n 100 -c 100 baidu.com/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking baidu.com (be patient).....done


Server Software:        Apache
Server Hostname:        baidu.com    #请求对方主机名
Server Port:            80    #对方主机名端口

Document Path:          /    #页面目录
Document Length:        81 bytes    #页面大小

Concurrency Level:      100    #并发级别100
Time taken for tests:   0.269 seconds    #测试花费时间
Complete requests:      100    #完成100请求
Failed requests:        0    #错误数量0
Write errors:           0    #写错误0
Total transferred:      38100 bytes    #共传输字节 包含tcp字节等
HTML transferred:       8100 bytes    #HTML字节,
Requests per second:    371.69 [#/sec] (mean)    #每秒完成数量
Time per request:       269.044 [ms] (mean)    #每一批请求需要消耗的时间
Time per request:       2.690 [ms] (mean, across all concurrent requests) #单个请求需要耗费时间
Transfer rate:          138.29 [Kbytes/sec] received    #传输速率 X8 =带宽

Connection Times (ms)
              min(最小)  mean[+/-sd] median    (平均)   max(最大)
Connect:       28                       78  14.0     82          93        建立连接
Processing:    35                       91  18.3    100         114        服务器端处理请求
Waiting:       30                       90  18.5    100         113        服务器端发送响应
Total:         63                      169  30.4    182         202     完整完成请求

Percentage of the requests served within a certain time (ms)
  50%    182
  66%    190
  75%    193
  80%    196
  90%    197
  95%    201
  98%    202
  99%    202
 100%    202 (longest request)

6、httpd自带的工具程序

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





原文地址:https://www.cnblogs.com/Mahavairocana/p/8151433.html