httpd配置

httpd的特性

高度模塊化:核心模塊+功能模塊; 
DSO (Dynamic share object ):動態裝卸載; 
多路處理模塊機制:MPM( Multipath processing Modules);

Prefork: 多進程模型,每個進程響應一個請求,一個主進程,多個子進程;主進程負責生成子進程(工作進程)以處理用戶的請求,也負責回收子進程,創建套接字進程,接受請求并派發給某子進程進行處理;子進程只負責處理請求; 
Worker: 多進程多線程模型,每個進程生成多個線程,每個線程響應一個請求;一個主進程,多個子進程;主進程負責生成子進程(工作進程)以處理用戶的請求,也負責回收子進程,創建套接字進程,接受請求并派發給某子進程進行處理;每個子進程只負責生成多個線程;每個線程負責響應用戶的請求; 
Event: 事件驅動模型,一個進程響應多個請求;一個主進程,多個子進程;主進程負責生成子進程(工作進程)以處理用戶的請求,也負責回收子進程,創建套接字進程,接受請求并派發給某子進程進行處理;每個子進程基于事件驅動機制直接響應多個請求;

Httpd功能特性

CGI: Common Gateway Interface 
虛擬主機:基于IP,基于端口,基于FQDN 
反向代理 
負載均衡 
路徑別名 
豐富的用戶認證機制

Basic:明文 
Digest:摘要

支持擴展的第三方模塊

httpd的安裝

httpd的版本:

1.3:停止維護 
2.0: 
2.2:CentOS 6默認版本, event仍為測試使用模型 
2.4:CentOS 7 默認版本, event可生產環境使用 
有3中安裝方式:rpm包安裝、yum源安裝、源碼編譯安裝。

在CentOS 6中安裝

使用的是yum源安裝,安裝完成后: 
由于在CentOS 6上的2.2版本由于不支持MPM動態切換,所以主程序文件有:/usr/sbin/httpd、/usr/sbin/httpd.event、/usr/sbin/httpd.worker 
配置文件:/etc/httpd/conf/httpd.conf(主配置文件)、/etc/httpd/conf.d/*.conf、/etc/sysconfig/httpd(腳本配置文件); 
日志文件目錄:/var/log/httpd/access.log、/var/log/httpd/error.log 
站點文檔:/var/www/html 
服務控制和啟動:service {start|stop|reload} httpd 、chkconfig httpd on|off

在CentOS 7中安裝

yum源安裝的是2.4版本,支持MPM動態切換,安裝完成后主程序文件只有一個:/usr/sbin/httpd 
配置文件:/etc/httpd/conf/httpd.conf、/etc/httpd/conf.d/*.conf 
服務文件:/usr/lib/systemd/system/httpd.service 
日志文件:/var/log/httpd/access.log、/var/log/httpd/error.log 
站點文檔:/var/www/html 
服務控制和啟動:systemctl enable | disable httpd.servic 和 systemctl {start | stop | restart | status } httpd.service

httpd的配置(CentOS 6)

在主配置文件/etc/httpd/conf/httpd.conf中,只要有3部分: 
###Section 1:Global Environment 
###Section 2:’Main’ Server configuration (默認) 
###Section 3:Virtual Hosts

[root:rc1.d]#    cat /etc/httpd/conf/httpd.conf
#
# This is the main Apache server configuration file.  It contains the
...
# server as "/etc/httpd/logs/foo.log".
#

### Section 1: Global Environment    ####################
#
# 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.

...
Group apache

### Section 2: 'Main' server configuration    ###############
#
# The directives in this section set up the values used by the 'main'
...
### Section 3: Virtual Hosts      ############
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
...

配置格式 
指令行:指令 Directive:value

Directive :不區分字符大小寫,但是字符首位應該大寫 
Value :作為路徑時候,是否區分字符大小寫,取決于文件系統 
注意:修改監聽的socket,只有重啟服務進程方可生效。

修改監聽的IP和端口(port)

[root:rc1.d]#    vim /etc/httpd/conf/httpd.conf
...
128 # Listen: Allows you to bind Apache to specific IP addresses and/or
129 # ports, in addition to the default. See also the <VirtualHost>
130 # directive.
131 #
132 # Change this to Listen on specific IP addresses as shown below to
133 # prevent Apache from glomming onto all bound IP addresses (0.0.0.0)
134 #
135 #Listen 12.34.56.78:80
136 Listen 80
...

格式為:Listen IP:PORT,如上面的配置中,沒有指定IP,就是默認的0.0.0.0:80,就是httpd服務器上面的所有的ip的80端口。也可以指定不同的IP和不同的PORT,Listen語句可以出現多次:

 135 #Listen 12.34.56.78:80
136 Listen 80
137 Listen 172.16.253.184:8080

修改完配置文件后,保存。并且重啟服務。

持久連接

  ...
 72 #
 73 # KeepAlive: Whether or not to allow persistent connections (more than
 74 # one request per connection). Set to "Off" to deactivate.
 75 #
 76 KeepAlive Off
 77
 78 #
 79 # MaxKeepAliveRequests: The maximum number of requests to allow
 80 # during a persistent connection. Set to 0 to allow an unlimited amount.
 81 # We recommend you leave this number high, for maximum performance.
 82 #
 83 MaxKeepAliveRequests 100
 84
 85 #
 86 # KeepAliveTimeout: Number of seconds to wait for the next request from the
 87 # same client on the same connection.
 88 #
 89 KeepAliveTimeout 15
...

如上,KeepAlive Off | On來控制開始或者關閉KeepAlive功能;KeepAliveTimeout 15持久連接的持續時間為:15秒;MaxKeepAliveRequests 100最大的持久連接為100。在訪問并發數量較大的服務器上,通過通過調節持久連接的持續時間和最大連接數來達到最好的訪問效果。

MPM

httpd2.2不支持同時編譯多個MPM模塊,只能編譯選定要使用的模塊。在CentOS 6提供的rpm有3個應用程序:httpd(prefork)、httpd.worker、httpd.event。默認的使用的是prefork模塊。要想查看已轉載的模塊,使用:

[root:rc1.d]#    httpd -l
Compiled in modules:
 core.c
 prefork.c      ###使用是prefork模塊
 http_core.c
 mod_so.c

查看動態裝載模塊:

[root:rc1.d]#    httpd -M
Loaded Modules:
core_module (static)
mpm_prefork_module (static)
http_module (static)
so_module (static)
auth_basic_module (shared)
auth_digest_module (shared)
authn_file_module (shared)
...
version_module (shared)
dnssd_module (shared)
Syntax OK

要想更換使用的模塊,打開腳本配置文件/etc/sysconfig/httpd:

  1 # Configuration file for the httpd service.
 2
 3 #
 4 # The default processing model (MPM) is the process-based
 5 # 'prefork' model.  A thread-based model, 'worker', is also
 6 # available, but does not work with some modules (such as PHP).
 7 # The service must be stopped before changing this variable.
 8 #
 9 #HTTPD=/usr/sbin/httpd.worker
10
11 #
12 # To pass additional options (for instance, -D definitions) to the
13 # httpd binary at startup, set OPTIONS here.
14 #
15 #OPTIONS=
16

上圖的第九行,修改為HTTPD=/usr/sbin/httpd.worker或者HTTPD=/usr/sbin/httpd.event,然后重啟服務即可。 
注意:對Linux而言,線程是跟進程一樣的量級,多線程模型所能帶來的性能的提升是有效的。 Worker和prefork的性能并沒有太大的改變。 
使用prefork模塊的配置:

     # prefork MPM
 96 # StartServers: number of server processes to start
 97 # MinSpareServers: minimum number of server processes which are kept spare
 98 # MaxSpareServers: maximum number of server processes which are kept spare
 99 # ServerLimit: maximum value for MaxClients for the lifetime of the server
100 # MaxClients: maximum number of server processes allowed to start
101 # MaxRequestsPerChild: maximum number of requests a server process serves
102 <IfModule prefork.c>         ##如是轉載的是prefork.c模塊
103 StartServers       8    ##服務器進程啟動時候啟動多少空閑進程
104 MinSpareServers    5  ##最少空閑進程數,如果少于5,主控進程再啟動幾個達到5
105 MaxSpareServers   20  ##最大空閑進程數,如果大于20主控進程對子進程進行回收
106 ServerLimit      256  ##所允許啟動的最大在線進程數量
107 MaxClients       256  ##最大允許啟動進程數量響應用戶請求(最大并發響應數)
108 MaxRequestsPerChild  4000  ##4000 每個進程最多可以處理多少個請求,超過4000銷毀
109 </IfModule>

使用worker模塊的配置:

111 # worker MPM
112 # StartServers: initial number of server processes to start
113 # MaxClients: maximum number of simultaneous client connections
114 # MinSpareThreads: minimum number of worker threads which are kept spare
115 # MaxSpareThreads: maximum number of worker threads which are kept spare
116 # ThreadsPerChild: constant number of worker threads in each server process
117 # MaxRequestsPerChild: maximum number of requests a server process serves
118 <IfModule worker.c>
119 StartServers         4  ##服務器進程啟動時候啟動多少空閑進程
120 MaxClients         300  ##最大并發響應數
121 MinSpareThreads     25  ##最小空閑線程數
122 MaxSpareThreads     75  ##最大空閑線程數
123 ThreadsPerChild     25  ##每個進程啟動25個線程
124 MaxRequestsPerChild  0  ##每個進程可以處理無限個請求
125 </IfModule>

注意:Httpd在Worer 模式下先啟動4個子進程,然后再銷毀一個,通過watch可以觀察: 
Watch -n.5 ‘ ps aux | grep httpd’

DSO(Dynamic Shared Object)

動態裝載模塊的實現:LoadModules < mod_name >< mod_path >,路徑使用的相對路徑,相對于ServerRoot(默認為/etc/httpd)。 
在/etc/httpd/conf/http.conf中:

 139 # Dynamic Shared Object (DSO) Support
140 #
141 # To be able to use the functionality of a module which was built as a DSO you
142 # have to place corresponding `LoadModule' lines at this location so the
143 # directives contained in it are actually available _before_ they are used.
144 # Statically compiled modules (those listed by `httpd -l') do not need
145 # to be loaded here.
146 #
147 # Example:
148 # LoadModule foo_module modules/mod_foo.so
149 #
150 LoadModule auth_basic_module modules/mod_auth_basic.so
151 LoadModule auth_digest_module modules/mod_auth_digest.so
152 LoadModule authn_file_module modules/mod_authn_file.so
153 LoadModule authn_alias_module modules/mod_authn_alias.so
154 LoadModule authn_anon_module modules/mod_authn_anon.so
155 LoadModule authn_dbm_module modules/mod_authn_dbm.so
156 LoadModule authn_default_module modules/mod_authn_default.so
157 LoadModule authz_host_module modules/mod_authz_host.so
...

main server的文檔頁面路徑

在/etc/httpd/conf/httpd.conf文件中,定義頁面路徑語句為:

# DocumentRoot: The directory out of which you will serve your
289 # documents. By default, all requests are taken from this directory, but
290 # symbolic links and aliases may be used to point to other locations.
291 #
292 DocumentRoot "/var/www/html"   ##默認的路徑,安裝完成后就存在的路徑

在使用yum源安裝完成后,啟動httpd服務,大概瀏覽器,輸入本機ip,有一個歡迎頁面,該也頁面路徑如下:/etc/httpd/conf.d/welcome.conf,刪除掉或者改名后,就沒有歡迎頁面了。 
DocumentRoot “/var/www/html”后面的路徑可以更改為你自己想要的路徑,更改完成后,重啟服務。

[root:modules]#    vim /etc/httpd/conf/httpd.conf
...
290 # symbolic links and aliases may be used to point to other locations.
291 #
292 DocumentRoot "/www/html"   ###更改路徑為/www/html
293
...
[root:~]#    mkdir -p /www/html   ##創建目錄
[root:~]#    echo "hello china" > /www/html/index.html    ##創建文件并輸入數據
[root:~]#    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  ]

通過links軟件查看:

[root:~]#    links 127.0.0.1
                                                                                                                                                      http://127.0.0.1/
  hello china                                                                                                              

本主機上有兩張網卡,也可以通過指定監聽某一個ip上:

[root:~]#    ip a
...
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
   link/ether 00:0c:29:bb:1c:30 brd ff:ff:ff:ff:ff:ff
   inet 172.16.253.184/16 brd 172.16.255.255 scope global eth1
 ...
[root:~]#    vim /etc/httpd/conf/httpd.conf
...
135 #Listen 12.34.56.78:80
136 #Listen 80
137 Listen 172.16.253.184:8080
138 #
...
[root:~]#    !serv
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  ]

通過上面的修改,只監聽172.16.253.184:8080,其他的ip不監聽。因此只有它才能訪問。

[root:~]#    links 172.16.253.184:8080
                                                                                                                                            http://172.16.253.184:8080/
  hello china
###而用其他的本機ip則訪問不了。

站點訪問控制

對于站點訪問的控制,可基于兩種機制,指明對那些資源進行何種訪問: 
1、文件系統路徑; 
2、URL路徑; 
文件系統路徑:

<Directory "">
...
</Directory>
或者
<File "">
...
</File>
或者
<FileMatch "PATTERN">
...
</FileMatch>

URL路徑:

<Location "">
...
</Location>
或者
</LocationMatch "">
...
</LocationMatch>

下面就是一個基于文件系統路徑的站點訪問控制的實例:

 316 #
317 <Directory "/var/www/html">
318
319 #
320 # Possible values for the Options directive are "None", "All",
321 # or any combination of:
322 #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
323 #
324 # Note that "MultiViews" must be named *explicitly* --- "Options All"
325 # doesn't give it to you.
326 #
327 # The Options directive is both complicated and important.  Please see
328 # http://httpd.apache.org/docs/2.2/mod/core.html#options
329 # for more information.
330 #
331     Options Indexes FollowSymLinks
332
333 #
334 # AllowOverride controls what directives may be placed in .htaccess files.
335 # It can be "All", "None", or any combination of the keywords:
336 #   Options FileInfo AuthConfig Limit
337 #
338     AllowOverride None
339
340 #
341 # Controls who can get stuff from this server.
342 #
343     Order allow,deny
344     Allow from all
345
346 </Directory>

Options定義此目錄內資源訪問的特性,控制被定義的目錄下所指定的各種資源的被訪問模式(方式),后跟一個或多個以空白字符分割的選項列表:

Indexes:指明的URL路徑不存在與定義的主頁面資源相符的資源文件時候,返回索引列表給用戶,目錄瀏覽功能,一般關掉: 
[root:~]# cd /var/www/html/ 
[root:html]# ls 
[root:html]# echo “hello world! ” > index1.html 
[root:html]# echo “hello mage! ” > index2.html 
[root:html]# ls 
index1.html index2.html 
[root:html]# mv /etc/httpd/conf.d/welcome.conf /etc/httpd/conf.d/welcome.conf.bak 
[root:html]# 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 ] 
[root:html]# links 127.0.0.1

[ICO] Name Last modified Size Description 
════════════════════════════════════════════════════ 
[TXT] index1.html 11-Dec-2016 15:29 14 
[TXT] index2.html 11-Dec-2016 15:29 13 
════════════════════════════════════════════════════ 
Apache/2.2.15 (CentOS) Server at 127.0.0.1 Port 80 
Indexes將根路徑下的所有頁面都列出來了,則是一件較危險的事情,所以一般關掉。關掉后:

 330 #
331     Options FollowSymLinks
332

顯示為:

[root:html]# links 127.0.0.1 
403 Forbidden 
Forbidden

You don’t have permission to access / on this server.

═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ 
Apache/2.2.15 (CentOS) Server at 127.0.0.1 Port 80 
FollowSymLinks 允許跟蹤符號鏈接文件所指向的源文件跟蹤符號鏈接,如果目錄下存在軟連接,則可以直接訪問軟連接指向的文件;

[root:html]#    cp -s /etc/issue index.html
[root:html]#    ls
index1.html  index2.html  index.html
[root:html]#    ll
total 8
-rw-r--r-- 1 root root 14 Dec 11 15:29 index1.html
-rw-r--r-- 1 root root 13 Dec 11 15:29 index2.html
lrwxrwxrwx 1 root root 10 Dec 11 15:42 index.html -> /etc/issue
[root:html]#    !ser
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  ]
[root:html]#    links 127.0.0.1
                                                                                                                                                      http://127.0.0.1/
  CentOS release 6.7 (Final) Kernel \r on an \m Mage Education Learning Services http://www.magedu.com

后面顯示的內容為issue文件的內容。

Includes: 允許啟用服務端包含 
SymLinksifOwnerMatch: 源文件和鏈接的目標文件的屬主屬組相同的時候才允許跟蹤訪問 
ExecCGI: 允許執行CGI腳本 
MultiViews: 允許執行內容協商 
None:全部都不 
ALL: 所有都

 337 #
338     AllowOverride None
339

AllowOverride:與訪問控制相關的哪些執行可以放在.htacesss文件中,每個目錄下都可以有一個 ,但是使用.htacess會使得網站對目錄下的資源解析變的非常慢,不推薦使用。 ALL所有都可以放進去, None什么都不可以放。

 342 #
343     Order allow,deny
344     Allow from all
345

Order 定義生效法則,寫在后面表示默認法則; 
Allow from all,Deny from 來源地址IP或者網絡地址:

網絡地址格式: 
172.16 
172.16.0.0 
172.16.0.0/16 
172.16.0.0/255.255.0.0 
舉例:

Order allow,deny
Allow from 172.16   ##僅允許172.16網段的地址訪問
Order allow,deny
Deny from 172.16.12.1
Allow from 172.16   ##僅允許172.16網段除172.16.12.1的地址訪

定義站點主頁面

     # The index.html.var file (a type-map) is used to deliver content-
399 # negotiated documents.  The MultiViews Option can be used for the
400 # same purpose, but it is much slower.
401 #
402 DirectoryIndex index.html index.html.var  從左到右優先

當請求的資源不存在的時候 http服務器會有兩種處理結果: 
1 返回404或者403 
2 將當前網頁目錄下內容全部列出來

定義路徑別名

定義路徑別名的方式為:Alias /URL/ “/PATH/TO/SOMEDIR” 
/etc/httpd/conf/httpd.conf中定義了DocumentRoot /var/www/html,訪問的URL:http://127.0.0.1/roger/index.html即使訪問的是/var/www/html/下面的roger/index.html。

[root:html]#    links 127.0.0.1/roger/index.html
                                                                                                                                                      http://127.0.0.1/roger/index.html
                                                                                                                                                         hello world!

現在在/etc/httpd/conf/httpd.conf中加入一行:

 293 Alias /roger/ "/www/html/"

并編輯文件:

[root:html]#    cat /www/html/index.html
hello china

重啟服務并查看:

[root:html]#    links 127.0.0.1/roger/index.html
                                                                                                                                      http://127.0.0.1/roger/index.html
  hello china

通過上述的實驗表明,別名為: 
當你定義別名為 Alias /roger/ “/www/html/” 時,當你訪問http://127.0.0.1/roger/index.html時,不再是訪問的是定義的DocumentRoot “/var/www/html”下面的roger/index.html ,而是訪問的是/www/html/index.html 。

設定默認字符集

 757 # directive:
758 #
759 AddDefaultCharset UTF-8
760

常用的中文字符集有:UTF-8 、GBK、GB2312、GB18030。

日志

錯誤日志:

 478 # ErrorLog: The location of the error log file.
479 # If you do not specify an ErrorLog directive within a <VirtualHost>
480 # container, error messages relating to that virtual host will be
481 # logged here.  If you *do* define an error logfile for a <VirtualHost>
482 # container, that host's errors will be logged there and not here.
483 #
484 ErrorLog logs/error_log
485
486 #
487 # LogLevel: Control the number of messages logged to the error_log.
488 # Possible values include: debug, info, notice, warn, error, crit,
489 # alert, emerg.
490 #
491 LogLevel warn
492
493 #
494 # The following directives define some format nicknames for use with
495 # a CustomLog directive (see below).
496 #
497 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
498 LogFormat "%h %l %u %t \"%r\" %>s %b" common
499 LogFormat "%{Referer}i -> %U" referer
500 LogFormat "%{User-agent}i" agent

ErrorLog logs/error_log 定義日志,相對于/etc/httpd目錄,即/etc/httpd/logs/error_log 。

[root:html]#    cd /etc/httpd/
[root:httpd]#    ll
...
lrwxrwxrwx  1 root root   19 Dec  9 10:50 logs -> ../../var/log/httpd
...
 490 #
491 LogLevel warn
492

定義的錯誤日志級別為:warn 
錯誤日志有如下的級別:

debug, 所有信息,只要產生就全部記錄下來 
info, 所有的信息數據 
notice, 引起注意 
warn, 警告 
error, 發生錯誤 
crit, 級別很嚴重 
alert, 紅色警戒 
emerg. 引起恐慌

訪問日志

 525 #
526 CustomLog logs/access_log combined
527

格式 日志路徑 日志格式( combined | common | referer|agent )

日志格式:

 496 #
497 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
498 LogFormat "%h %l %u %t \"%r\" %>s %b" common
499 LogFormat "%{Referer}i -> %U" referer
500 LogFormat "%{User-agent}i" agent  

%h:客戶端ip; 
%l:遠程用戶名,通常為“-”; 
%u:遠程用戶,為非登錄訪問是為“-”; 
%t:服務器收到請求時的時間; 
%r:請求報文的首行,記錄了此次請求的方法、URL以及協議版本; 
%s:狀態信息; 
%b:響應報文大小,不包括響應報文的http首部; 
%{Referer}i:請求報文中的Referer的值,即從哪個頁面的超鏈接跳轉到本頁面的; 
%{User-agent}i:請求報文中首部的User-agent值,即發出請求的應用程序;

實例:

[root:httpd]#    cat /etc/httpd/logs/access_log
172.16.253.113 - - [09/Dec/2016:10:55:54 +0800] "GET /?release=6&arch=x86_64&repo=os&infra=stock HTTP/1.1" 403 4961 "-" "urlgrabber/3.9.1 yum/3.2.29"
...
127.0.0.1 - - [11/Dec/2016:16:21:25 +0800] "GET /roger/index.html HTTP/1.1" 200 14 "-" "ELinks/0.12pre5 (textmode; Linux; 169x34-2)"
127.0.0.1 - - [11/Dec/2016:16:29:15 +0800] "GET /roger/index.html HTTP/1.1" 200 12 "-" "ELinks/0.12pre5 (textmode; Linux; 169x34-2)"

基于用戶的訪問控制

htppd協議自帶的認證方式為:

basic :明文認證 
表單認證:digest消息摘要認證

認證質詢

www-authenticate:響應碼為401, 拒絕客戶端請求,并說明要求客戶端提供賬號密碼; 
Authorization:客戶端用戶填入賬號密碼后再次發送請求報文,認證通過時,則服務器發送響應的資源; 
安全域:需要用戶認證后方能訪問的路徑。 應該通過名稱對其進行標示,以便于告知用戶認證的原因; 
用戶賬號密碼存放位置

虛擬賬號: 僅用于訪問某服務時候用到的認證標識 
存儲:文件文件、 SQL數據庫、 LDAP 輕量級目錄訪問協議

Basic認證的步驟: 
1、定義安全域:

<Directory “”>
Options None
AllowOverride None
AuthType Basic
AuthName “String
AuthUserFile “/PATH/TO/HTTPD_USER_PASSWD_FILE”
# AuthgroupFile “/PATH/TO/HTTPD_GROUP_FILE” #基于組來認證
Require user username1 username2...
# Require group grpname1 grpname2 ...
</Directory >

2、創建賬號密碼

 htpasswd -c -m /etc/httpd/conf/.htpasswd roger
-c 第一次創建密碼文件的時候使用
-m MD5認證
htpasswd選項
? -n Don't update file; display results on stdout.
? -m Force MD5 encryption of the password.
? -d Force CRYPT encryption of the password (default).
CRYPT加密
? -p Do not encrypt the password (plaintext).
? -s Force SHA encryption of the password.
? -b Use the password from the command line rather than
prompting for it.
? -D Delete the specified user. 刪除一個用戶

實例: 
/etc/httpd/conf/httpd.conf中新建一個安全域:

 296 <Directory "/www/html/">
297 Options None
298 AllowOverride None
299 AuthType Basic
300 AuthName "Please enter roger's passwd."
301 AuthUserFile "/etc/httpd/conf/.htpasswd"
302 Require user roger
303 #Require user vaild-user //允許所有用戶登錄
304 </Directory>

創建用戶:

[root:httpd]#    htpasswd -c -m /etc/httpd/conf/.htpasswd roger
New password:
Re-type new password:
Adding password for user tom
[root:conf]#    links 127.0.0.1/roger/index.html

輸入賬號密碼刷新頁面:

如果要使用用戶文件中的所用用戶登錄,這編輯如下:

 296 <Directory "/www/html/">
297 Options None
298 AllowOverride None
299 AuthType Basic
300 AuthName "Please enter roger's passwd."
301 AuthUserFile "/etc/httpd/conf/.htpasswd"
302 Require  valid-user      ###這就話定義了用戶文件中的所有用戶可以登錄
303 #AuthGroupFile "/etc/httpd/conf/.htgroup"
304 #Require group mygrp mygrp1
305 </Directory>

基于用戶組的認證: 
編輯文件如下:

 295
296 <Directory "/www/html/">
297 Options None
298 AllowOverride None
299 AuthType Basic
300 AuthName "Please enter roger's passwd."
301 AuthUserFile "/etc/httpd/conf/.htpasswd"   ##
302 AuthGroupFile "/etc/httpd/conf/.htgroup"  ##這三行都必須要有
303 Require group mygrp mygrp1  ##指定組
304 </Directory>

編輯.htgroup文件:

 1 mygrp:wang wang1 wang2 wang3 wang4
2 mygrp1:wang5 wang6 wang7

將.htgroup中的用戶使用命令 htpasswd -m /etc/httpd/conf/.htpasswd添加到用戶文件中。 
然后重啟服務。就可以使用組里面的用戶訪問頁面了。

虛擬主機

在設置虛擬主機之前,需要將DocumentRoot語句注釋掉,以禁用main主機。 
虛擬主機的實現方式

基于IP 為每個虛擬主機至少準備一個IP地址 
基于port 為每個虛擬主機至少一個獨立的port 
基于FQDN 每個虛擬主機至少一個FQDN

配置語法:

<VirtualHost IP:PORT>
ServerAlias 虛擬主機的別名,可多次使用
Errorlog 專用的錯誤日志
CustomLog 專用的自定義日志
<Directory “”></Directory> 對資源做訪問控制
ServerName FQDN
DocumentRoot “” //站點路徑
</VirtualHost>

基于IP 為每個虛擬主機至少準備一個IP地址

禁用Main主機:

 292 #DocumentRoot "/var/www/html"

可以在/etc/httpd/conf/httpd.conf中直接編輯,也可以在conf.d中創建一個文件。

[root:conf.d]#    vim vhost.conf
 1 <VirtualHost 172.16.100.101:80>
 2 DocumentRoot /www/html
 3 ServerName www.roger.com
 4 ErrorLog logs/www.roger.com-error_log
 5 CustomLog logs/www.roger.com-access_log common
 6 </VirtualHost>
 7
 8
 9 <VirtualHost 172.16.253.184:80>
10 DocumentRoot /www/html1
11 ServerName www.roger1.com
12 ErrorLog logs/www.roger1.com-error_log
13 CustomLog logs/www.roger1.com-access_log common
14 </VirtualHost>
[root:www]# cd /www/
[root:www]# mkdir html1
[root:www]# echo "172.16.100.101" > html/index.html
[root:www]# echo "172.16.253.184" > html1/index.html

配置完成后,重啟服務,即可在瀏覽器上面瀏覽。

基于port 為每個虛擬主機至少一個獨立的port

編輯vhost.conf文件:

  1 Listen 8000      ##添加需要監聽的其他端口
 2 <VirtualHost 172.16.100.101:80>
 3 DocumentRoot /www/html
 4 ServerName www.roger.com
 5 ErrorLog logs/www.roger.com-error_log
 6 CustomLog logs/www.roger.com-access_log common
 7 </VirtualHost>
 8
 9
10 <VirtualHost 172.16.100.101:8000>
11 DocumentRoot /www/html1
12 ServerName www.roger1.com
13 ErrorLog logs/www.roger1.com-error_log
14 CustomLog logs/www.roger1.com-access_log common
15 </VirtualHost>

編輯完成重啟服務,即可查看:

[root:www]#    links 172.16.100.101:8000
                                                                                                                                            http://172.16.100.101:8000/
  172.16.253.184
[root:www]#    links 172.16.100.101
                                                                                                                                                 http://172.16.100.101/
  172.16.100.101

基于FQDN 每個虛擬主機至少一個FQDN

編輯vhost.conf如下:

  1 NameVirtualHost 172.16.100.101   ###
 2 NameVirtualHost 172.16.253.184  ###這兩行在2.2版本中必須加,在2.4版本中就不用加入
 3 <VirtualHost 172.16.100.101:80>
 4 DocumentRoot /www/html
 5 ServerName www.roger.com
 6 ErrorLog logs/www.roger.com-error_log
 7 CustomLog logs/www.roger.com-access_log common
 8 </VirtualHost>
 9
10
11 <VirtualHost 172.16.253.184:80>
12 DocumentRoot /www/html1
13 ServerName www.roger1.com
14 ErrorLog logs/www.roger1.com-error_log
15 CustomLog logs/www.roger1.com-access_log common
16 </VirtualHost>

然后添加hosts記錄:

  1 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
 2 ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
 4 172.16.100.101 www.roger.com
 5 172.16.253.184 www.roger1.com

重啟服務后:

[root:conf.d]#    links www.roger.com
                                                                                                                                                  http://www.roger.com/
  172.16.100.101
[root:conf.d]#    links www.roger1.com
                                                                                                                                                 http://www.roger1.com/
  172.16.253.184

httpd狀態頁面

要啟用狀態頁面。必須加載狀態頁面模塊

 178 LoadModule status_module modules/mod_status.so

開啟狀態頁面:

 933 #
934 <Location /server-status>
935     SetHandler server-status
936     Order deny,allow
937     Deny from all
938     Allow from 172.16.0.0/16
939 </Location>

設置允許訪問狀態頁面的ip段或其他的主機等。 
設置完重啟服務:

[root:conf.d]#    links www.roger.com/server-status
[root:conf.d]#    hostname roger  ##設置主機名
                                                                                                                Apache 
Status (1/2)
                                                                Apache Server Status for www.roger.com

  Server Version: Apache/2.2.15 (Unix) DAV/2                  

  Server Built: Nov 18 2016 23:48:55                          

  ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════

  Current Time: Sunday, 11-Dec-2016 20:08:43 CST                                                                      

  Restart Time: Sunday, 11-Dec-2016 20:06:32 CST                                                                      

  Parent Server Generation: 0                                                                                          

  Server uptime: 2 minutes 11 seconds                                                                                  

  1 requests currently being processed, 7 idle workers                                                                

W_______........................................................                                                      
................................................................                                                      
................................................................                                                      
................................................................                                                      

 
Scoreboard Key:                                                                                                      
  "_" Waiting for Connection, "S" Starting up, "R" Reading Request,                                                    
  "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
  "C" Closing connection, "L" Logging, "G" Gracefully finishing,
  "I" Idle cleanup of worker, "." Open slot with no current process

  PID Key:

   7280 in state: W ,   7281 in state: _ ,   7282 in state: _
OK                                                                                                                                                              [------]

上圖解釋:

 W_______........................................................                                                       
................................................................                                                      
................................................................                                                      
................................................................

W正處在工作狀態,發送響應報文進程 
等待連接請求 
.代表還可以開啟的進程,該主機最多256個進程,由下面的設置決定:

 102 <IfModule prefork.c>
103 StartServers       8
104 MinSpareServers    5
105 MaxSpareServers   20
106 ServerLimit      256
107 MaxClients       256
108 MaxRequestsPerChild  4000
109 </IfModule>

S 正在創建 
R 正在讀取請求 
K 正在保持連接中 
D 正在執行DNS查詢 
C 正在關閉連接 
L 正在記錄日志 
G 正在優雅關閉 
I 空閑清理 
注意:狀態頁面通常只對個別對象開放,一般都關閉(注釋掉)

使用壓縮模塊mod_daflate優化速度

httpd2.2

在主配置文件httpd.conf中加入以下設置:

SetOutputFilter DEFLATE
   AddOutputFilterByType DEFLATE text/plain
   AddOutputFilterByType DEFLATE text/html
   AddOutputFilterByType DEFLATE application/xhtml+xml
   AddOutputFilterByType DEFLATE application/x-javascript
   AddOutputFilterByType DEFLATE application/xml
   AddOutputFilterByType DEFLATE text/javascript
   AddOutputFilterByType DEFLATE text/css
   AddOutputFilterByType DEFLATE text/xml
DeflateCompressionLevel 5
BrowserMatch ^Mozilla/2 no-gzip
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

然后重啟httpd服務,使用谷歌或者火狐瀏覽器訪問網頁,大概調試窗口:

blob.png

響應的編碼是gzip格式。

httpd2.4

在httpd2.4上 面要使用壓縮頁面的方式優化速度,首先要啟用響應的模塊:

103 LoadModule deflate_module modules/mod_deflate.so

啟用模塊后,先重啟服務,再在http.conf中添加一段設置:

SetOutputFilter DEFLATE
   AddOutputFilterByType DEFLATE text/plain
   AddOutputFilterByType DEFLATE text/html
   AddOutputFilterByType DEFLATE application/xhtml+xml
   AddOutputFilterByType DEFLATE application/x-javascript
   AddOutputFilterByType DEFLATE application/xml
   AddOutputFilterByType DEFLATE text/javascript
   AddOutputFilterByType DEFLATE text/css
   AddOutputFilterByType DEFLATE text/xml
DeflateCompressionLevel 5
BrowserMatch ^Mozilla/2 no-gzip
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

重啟服務,在訪問網頁,查看調試窗口的Response HEADERS的Content-Encoding是否為壓縮格式。

原創文章,作者:王更生,如若轉載,請注明出處:http://www.www58058.com/64407

(0)
王更生王更生
上一篇 2016-12-21
下一篇 2016-12-21

相關推薦

  • N23_第五周

    1.顯示/boot/grub/grub.conf中以至少一個空白字符開頭的行 egrep “^[[:space:]]{1,}” /boot/grub/grub.conf 2.顯示/etc/rc.d/rc.sysinit文件中以#開頭,后面跟至少一個空白字符,而后又有至少一個非空白字符的行 egrep “^#[[:space:]]{1,}.*[^[:space…

    Linux干貨 2017-02-27
  • N25-第五周

    – 1     顯示/boot/grub/grub.conf中以至少一個空白字符開頭的行;     grep "^[[:space:]]\+" /boot/grub/grub.conf2 顯示/etc/rc.d/rc.sysinit文件中以#開頭,后面跟至少一個空白字符,而后又有至少一個非空白字符的…

    Linux干貨 2017-01-02
  • Infobright高性能數據倉庫

    1.  概述         Infobright是一款基于獨特的專利知識網格技術的列式數據庫。Infobright簡單易用,快速安裝部署,使用中無需復雜操作,能大幅度減少管理工作;在應對50TB甚至更多數據量進行多并發復雜查詢時,更能夠顯示出令人驚嘆的速度。相比于MySQL,其查詢速度提升了數倍甚…

    Linux干貨 2015-04-05
  • 優質代碼的十誡

    1.- DRY: Don’t repeat yourself. DRY 是一個最簡單的法則,也是最容易被理解的。但它也可能是最難被應用的(因為要做到這樣,我們需要在泛型設計上做相當的努力,這并不是一件容易的事)。它意味著,當我們在兩個或多個地方的時候發現一些相似的代碼的時候,我們需要把他們的共性抽象出來形一個唯一的新方法,并且改變現有的地方的代碼讓…

    Linux干貨 2015-04-01
  • ansible——自動化運維工具

    Ansible SSH-based configuration management, deployment, and task execution system 運維工具的分類: agent:基于專用的agent程序完成管理功能,puppet, func, zabbix, … agentless:基于ssh服務完成管理,ansible, fab…

    Linux干貨 2016-11-06
  • 字符切割和用戶管理

    1、列出當前系統上所有已經登錄的用戶的用戶名,同一個用戶登錄多次,則只顯示一次 who |cut -d’ ‘ -f1 |sort -u2、取出最后登錄到當前系統的用戶的相關信息。 last |head -1|cut -d’ ‘ -f1 3、取出當前系統上被用戶當作其默認shell的最多的那個shell。 cut…

    2017-12-17
欧美性久久久久