httpd配置文件詳解、虛擬主機實現、身份驗證實現

本文針對的是Server version: Apache/2.4.6 (CentOS)

1 httpd 命令

[root@node-43-200 ~]#httpd -h
Usage: httpd [-D name] [-d directory] [-f file]
             [-C "directive"] [-c "directive"]
             [-k start|restart|graceful|graceful-stop|stop]
             [-v] [-V] [-h] [-l] [-L] [-t] [-T] [-S] [-X]
Options:
  -D name            : define a name for use in <IfDefine name> directives
  -d directory       : specify an alternate initial ServerRoot
  -f file            : specify an alternate ServerConfigFile
  -C "directive"     : process directive before reading config files
  -c "directive"     : process directive after reading config files
  -e level           : show startup errors of level (see LogLevel)
  -E file            : log startup errors to file
  -v                 : show version number
  -V                 : show compile settings
  -h                 : list available command line options (this page)
  -l                 : list compiled in modules
  -L                 : list available configuration directives
  -t -D DUMP_VHOSTS  : show parsed vhost settings
  -t -D DUMP_RUN_CFG : show parsed run settings
  -S                 : a synonym for -t -D DUMP_VHOSTS -D DUMP_RUN_CFG
  -t -D DUMP_MODULES : show all loaded modules 
  -M                 : a synonym for -t -D DUMP_MODULES
  -t                 : run syntax check for config files
  -T                 : start without DocumentRoot(s) check
  -X                 : debug mode (only one worker, do not detach)

2 配置文件規則及常見指令

httpd核心是配置文件,各種功能都是都過配置文件來實現。使用yum安裝的默認主配置文件主要分爲幾類:
├── conf
│ ├── httpd.conf
│ └── magic
├── conf.d
│ ├── autoindex.conf
│ ├── README
│ ├── userdir.conf
│ └── welcome.conf
├── conf.modules.d
│ ├── 00-base.conf
│ ├── 00-dav.conf
│ ├── 00-lua.conf
│ ├── 00-mpm.conf
│ ├── 00-proxy.conf
│ ├── 00-systemd.conf
│ └── 01-cgi.conf
接下來按照以上目錄詳細說明各個模塊的作用。

2.1 httpd.conf 主配置文件

本文按照apache http主配置文件內容順序逐條講解。它包含給服務器指令的配置指令;更多的信息參考官方文檔
配置和日誌文件的命名:如果爲服務器顯示的用“/”指明路徑,則用的是絕對路徑,如果沒有“/”,用的則是相對路徑。

ServerRoot "/etc/httpd"

定義了配置文件、錯誤日誌等目錄的根,配置文件中的指令值的相對路徑都是以該目錄爲參考點。
不要在目錄路徑的末尾添加斜線。如果將serverroot指向非本地磁盤,請確保在mutex指令中指定一個本地磁盤(如果使用基於文件的互斥)。如果希望爲多個httpd守護進程共享同一個serverroot,則至少需要更改pidfile。

Listen 80
Listen 192.168.100.100:8080

Listen 指定一個IP或者端口來代替默認的80端口,端口,ip可以監聽多個。

Include conf.modules.d/*.conf

Include 指明加載模塊,所有該目錄下的conf文件指定的模塊都會加載。此處是加載模塊的總領,具體可以在conf.modules.d/目錄下修改
httpd啓動時候會自動解析配置文件,並在多出的解析中對重複項目進行合併,支持通配符*?[].include 指令值可以使用相對路徑也可以使用絕對路徑。如果include包含的文件不存在時,將報錯。這時可以使用 IncludeOptional 指令進行加載,這表示存在則加載,不存在就算了

User apache
Group apache

指定以哪個用戶,哪個組來運行httpd程序,因爲不用的用戶、組對系統的文件系統有不同的訪問權限。

ServerAdmin [email protected]

定義管理員郵箱,在某些自動生成的錯誤頁面中可能會使用該郵箱,展示給客戶端。

#ServerName www.example.com:80

用於唯一標識提供web服務的主機名,只有在基於名稱的虛擬主機中該指令纔是必須提供的。也就是說,如果不是在基於名稱的虛擬主機中,可以任意指定該指令的值,只要你認爲它能唯一標識你的主機。但如果不設置該指令,那麼httpd在啓動時,將會反解操作系統的IP地址
此項是默認關閉,一般服務程序會自動標明,但是我們也可以手動指定,防止程序啓動時候出現問題。如果沒有註冊的DNS域名,可以輸入IP地址

<Directory />
    AllowOverride none
    Require all denied
</Directory>

Directory 容器,作用是"對於匹配到的目錄,封裝一組指令,這些指令只作用於該目錄以及它的子目錄中的文件"。注意,< Directory >容器通常都是用絕對路徑,即< Directory /PATH/to/DIR >,如果使用相對路徑,則它相對於根文件系統的"/"
爲了系統安全,默認配置是決絕訪問服務系統的所有資源,如果想允許某個目錄訪問需要明確按照這種格式指出。
可以使用通配符,"“表示任意字符,”?“表示任意單個字符,”[]“表示範圍,如[a-z]、[0-9],但是這些通配符都不能匹配”/"。所以要跨目錄匹配時,必須顯式指定各個目錄的"/"符號。 <directory //public.html>無法匹配/home/user/public.html,但directory /home/*/public.html可以匹配。
它還可以使用正則表達式匹配,只需使用一個“~”符號即可。這時和使用< DirectoryMatch >、< FilesMatch >是一樣的,只不過Match類指令不需要使用"~"符號.
例如,下面的設置。其中後兩個Directory容器是等價的.匹配不區分大小寫的gif/jpg/jpeg/png

<FilesMatch "\.(?i:gif|jpe?g|png)$">
    Require all denied
</FilesMatch>

<Directory ~ "^/usr/local/apache/htdocs/[0-9]{3}">
    DirectoryIndex digest.html
</Directory>

<DirectoryMatch "^/usr/local/apache/htdocs/[0-9]{3}">
    DirectoryIndex digest.html
</DirectoryMatch>
DocumentRoot "/var/www/html"

默認的提供服務的根目錄,注意前文已經說過,指令值不要以“/”結尾,html目錄裏的內容就是網站的根目錄。

<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

寬鬆訪問:此格式定了寬鬆訪問的目錄,注意該處用的是絕對路徑,且用雙引號。

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

這是更寬鬆的訪問目錄權限,options 定義了可以訪問文件列表,以及軟連接文件的指向文件。AllowOverride 定義了.htaccess文件中允許使用的關鍵字,比如:all,none, options fileinfo authconfig limit等

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

該指令設置的是"當搜索的URL中的路徑使用了"/“結尾時,httpd將搜索該指令所指定的文件響應給客戶端”。也就是說,當url表示搜索的是目錄時,將查找該目錄下的DirectoryIndex。注意,很多時候如果沒有給定尾部的"/",httpd的dir_module模塊會自行加上"/",當然,是否補齊尾隨的"/",也是可以控制的。可以指定多個index文件,它們將按順序從左向右依次查找,並返回第一個找到的index文件。
DirectoryIndex指令可以設置在Server、Virtual host、Location和Directory上下文。所以,當設置在location或Directory容器中時,它將覆蓋全局設置。
當DirectoryIndex提供的索引文件都不存在時,將根據Options中的Indexes選項設置決定是否列出文件列表,除非是提供文件下載,否則出於安全考慮,這個選項是強烈建議關閉的

<Files ".ht*">
    Require all denied
</Files>

作用是對文件進行過濾,並授權,即同級目錄下的.ht*結尾的文件是不會被瀏覽器訪問的,這個文件一般有.htpasswd .htaccess 都是權限限制文件。當然如果有其他文件也可以指定。

ErrorLog "logs/error_log"

錯誤日誌記錄,此處定義了錯誤日誌的記錄文件。如果不指定虛擬主機容器的錯誤信息目錄,那麼虛擬主機錯誤記錄也會記錄在該文件。如果在虛擬主機容器裏指明瞭錯誤日誌的位置,那麼就不會再次記錄。

LogLevel warn

錯誤日誌的級別,一般包含這麼幾種:debug, info, notice, warn, error, crit,alert, emerg.

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>
    CustomLog "logs/access_log" combined
</IfModule>

條件判斷容器,在httpd啓動時進行檢測,IfModule log_config_module,如果加載了log_config_module模塊,封裝裏面的配置纔會生效。
log_config_module,logio_module是兩種模塊,實現了不同的功能。所以日誌記錄格式也會自定義不同。
這是模塊的定義模式,記錄配置模塊,嵌套了記錄信息模塊。在記錄配置模塊中可以配置很多中記錄的字段,並起別名,在記錄模塊裏可以指定用哪種格式。CustomLog “logs/access_log”,指明瞭訪問日誌的位置,注意此處用的是相對路徑,格式用的是combined指明的格式。

<IfModule alias_module>
	#Redirect permanent /foo http://www.example.com/bar
	# Alias /webpath /full/filesystem/path
	ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>

如果alias_module模塊加載,裏面封裝的指令纔會生效。
Redirect ,重定向,告訴客戶端,訪問的文檔存在,僅此而已。客戶端會發起一個新的請求,訪問新的url.
Alias,別名,對不存在的資源路徑進行映射。就是說/webpath其實並不存在於documentroot中,只是對/full/filesystem/path的別名。
ScriptAlias:定義了服務腳本的路徑,其實這也是一個別名,/cgi-bin/並不是真是存在的目錄。

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

賦予腳本目錄的完全訪問權。

<IfModule mime_module>
  TypesConfig /etc/mime.types
  AddType application/x-compress .Z
  AddType application/x-gzip .gz .tgz
  AddType text/html .shtml
  AddOutputFilter INCLUDES .shtml
</IfModule>

如果加載了mime_module,啓用相關的功能。
TypesConfig,指向mime.types文件,該文件定義了mime資源的各種後綴。
AddType application/x-compress .Z ,重寫原來的配置文件,額外增加文件類型,允許您讓某些瀏覽器動態解壓縮信息,不過有些瀏覽器可能不支持。
addhandler允許您將某些文件擴展名映射到“handlers”:與文件類型無關的操作。它們可以內置到服務器中,也可以與action指令一起添加。

AddDefaultCharset UTF-8

指定默認的字符集

<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>

mod_mime_magic模塊允許服務器使用來自文件本身內容的各種提示來確定其類型。mimemagicfile指令告訴模塊提示定義的位置

#EnableMMAP off
EnableSendfile on

定了mmap內存映射模型,是否啓用。發送文件是否啓用。

IncludeOptional conf.d/*.conf 

定了其他的配置文件路徑

3 httpd虛擬主機

httpd使用VirtualHost指令進行虛擬主機的定義。支持三種虛擬主機:基於ip,基於端口和基於名稱。其中基於端口的虛擬主機在httpd的術語上(例如官方手冊)也屬於基於IP的。
當一個請求到達時,將首先匹配虛擬主機。匹配虛擬主機的規則爲最佳匹配法。所謂最佳,是指通配的越少,匹配的優先級越高。例如"192.168.100.14:80"的優先級高於"*:80"。如果基於名稱的虛擬主機無法匹配上,則採用虛擬主機列表中的第一個虛擬主機作爲響應主機。如果所有虛擬主機都無法匹配上,則採用從主配置段落中的主機,如果主配置段落中註釋了DocumentRoot,則返回對應的錯誤。
主配置段落的指令基本上都能使用在虛擬主機容器中。至於虛擬主機中必須配有什麼指令,這沒有規定,因爲虛擬主機只是封裝一組指令而已,即使其中沒有任何指令,它也會從主配置段落中繼承。但是,既然要使用且已經使用了虛擬主機,按照常理來說,至少得提供不同的ServerName,DocumentRoot等指令以讓它們各自獨立。
最後需要說明的是,httpd的"-S"選項在調試虛擬主機配置選項時非常有用。

3.1 基於IP的虛擬主機

基於IP的虛擬主機是在不同的IP+PORT上提供不同的站點服務,最常見的是在不同端口上提供不同站點。
如果僅基於IP,即使用不同IP地址,那麼要求操作系統上有兩個或更多IP地址,可以提供多個網卡,或者通過網卡別名來實現。
如果基於端口,即使用不同端口,則使用相同IP或不同IP均可,但在httpd術語中,基於單個IP但不同端口的虛擬主機,也是基於IP的虛擬主機。

3.1.1 建立配置文件

本機IP爲192.168.122.100.在/etc/httpd/conf.d/下,默認此目錄下的conf文件,httpd啓動時候都會加載。

[root@node-43-200 httpd]#vim /etc/httpd/conf.d/vhost.conf 
<virtualHost 192.168.122.200:80>
    ServerName www.abc.com
    DocumentRoot vhosts/abc.com
</virtualHost>
<virtualHost 192.168.122.210:80>
    ServerName www.ab10.com
    DocumentRoot vhosts/ab10.com
</virtualHost>
<virtualHost 192.168.122.220:80>
    ServerName www.ab20.com
    DocumentRoot vhosts/ab20.com
</virtualHost>                                                                                                                                       
<Directory  "/etc/httpd/vhosts" >
Require all granted
</Directory>

此配過程中容器中不能定義端口信息,要使用main配置文件使用Listen端口。此處的80要和前面對應。此處端口也可以不寫,只寫明IP地址即可。

3.1.2 建立對應的虛擬網站的獨立目錄及文件。
cd /etc/httpd/
mkdir vhosts/{abc.com,ab10.com, ab20.com}
cd vhosts
echo ab10.com > ab10.com/index.html
echo ab20.com > ab20.com/index.html
echo abc.com > abc.com/index.html

使用httpd -S查看配置文件加載過程

[root@node-43-200 conf.d]#httpd -S -f /etc/httpd/conf/httpd.conf 
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using fe80::5054:ff:fe93:d3a9. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
192.168.122.210:80     www.ab10.com (/etc/httpd/conf.d/vhost.conf:5)
192.168.122.220:80     www.ab20.com (/etc/httpd/conf.d/vhost.conf:9)
192.168.122.200:80     www.abc.com (/etc/httpd/conf.d/vhost.conf:1)
ServerRoot: "/etc/httpd"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/etc/httpd/logs/error_log"
Mutex proxy-balancer-shm: using_defaults
Mutex rewrite-map: using_defaults
Mutex authdigest-client: using_defaults
Mutex proxy: using_defaults
Mutex authn-socache: using_defaults
Mutex default: dir="/run/httpd/" mechanism=default 
Mutex mpm-accept: using_defaults
Mutex authdigest-opaque: using_defaults
PidFile: "/run/httpd/httpd.pid"
Define: _RH_HAS_HTTPPROTOCOLOPTIONS
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="apache" id=48
Group: name="apache" id=48
3.1.3 增加IP
  ip addr add 192.168.122.210 dev eth0 label eth0:210
  ip addr add 192.168.122.220 dev eth0 label eth0:220
3.1.4 重啓服務,測試網頁
[root@node-43-200 conf.d]#systemctl restart httpd

在另外同網段機器上測試

[root@node-201 ~]#curl  192.168.122.200
abc.com
[root@node-201 ~]#curl  192.168.122.210
ab10.com
[root@node-201 ~]#curl  192.168.122.220
ab20.com

3.2 基於端口的虛擬主機

基於端口的虛擬主機需要監聽多個socket端口,所以首先要修改主配置文件的監聽端口信息。

Listen 192.68.122.200:80
Listen 192.68.122.200:808
Listen 192.168.122.200:8080

採用指定IP端口的形式。因爲主機有多個塊網卡,所以只指定了一個IP

[root@node-43-200 conf.d]#vim vhost.conf
<virtualHost 192.168.122.200:80>
    ServerName www.abc.com
    DocumentRoot vhosts/abc.com
</virtualHost>
<virtualHost 192.168.122.200:808>
    ServerName www.ab10.com
    DocumentRoot vhosts/ab10.com
</virtualHost>
<virtualHost 192.168.122.200:8080>
    ServerName www.ab20.com
    DocumentRoot vhosts/ab20.com
</virtualHost>
<Directory  "/etc/httpd/vhosts" >
Require all granted
</Directory>            

測試腳本.

[root@node-43-200 conf.d]#httpd  -S -f /etc/httpd/conf/httpd.conf 
VirtualHost configuration:
192.168.122.200:80     www.abc.com (/etc/httpd/conf.d/vhost.conf:1)
192.168.122.200:808    www.ab10.com (/etc/httpd/conf.d/vhost.conf:5)
192.168.122.200:8080   www.ab20.com (/etc/httpd/conf.d/vhost.conf:9)
ServerRoot: "/etc/httpd"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/etc/httpd/logs/error_log"
Mutex proxy: using_defaults
Mutex authn-socache: using_defaults
Mutex default: dir="/run/httpd/" mechanism=default 
Mutex mpm-accept: using_defaults
Mutex authdigest-opaque: using_defaults
Mutex proxy-balancer-shm: using_defaults
Mutex rewrite-map: using_defaults
Mutex authdigest-client: using_defaults
PidFile: "/run/httpd/httpd.pid"
Define: _RH_HAS_HTTPPROTOCOLOPTIONS
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="apache" id=48
Group: name="apache" id=48

重啓服務測試

[root@node-43-200 conf.d]#systemctl restart httpd
[root@node-201 ~]#curl  192.168.122.200:8080
ab20.com
[root@node-201 ~]#curl  192.168.122.200:808
ab10.com
[root@node-201 ~]#curl  192.168.122.200:80
abc.com

3.3 基於名稱的虛擬主機

請求報文中獲取資源時包含了兩部分資源定位的格式:TCP/IP協議和HTTP協議,雖然TCP/IP部分相同,但是HTTP協議的請求報文中指定了HOST,這就是基於域名的虛擬主機能實現的原因。也因此,基於名稱的虛擬主機必須指定ServerName指令,否則它將會繼承操作系統的FQDN。
修改配置文件

[root@node-43-200 conf.d]#cat /etc/httpd/conf.d/vhost.conf
<virtualHost 192.168.122.200>
    ServerName www.abc.com
    DocumentRoot vhosts/abc.com
</virtualHost>
<virtualHost 192.168.122.200>
    ServerName www.ab10.com
    DocumentRoot vhosts/ab10.com
</virtualHost>
<virtualHost 192.168.122.200>
    ServerName www.ab20.com
    DocumentRoot vhosts/ab20.com
</virtualHost>
<Directory  "/etc/httpd/vhosts" >
Require all granted
</Directory>

修改hosts文件

[root@node-43-200 conf.d]#cat /etc/hosts
192.168.122.200 www.abc.com www.ab10.com www.ab20.com

因爲沒搭建DNS,所以本機測試

[root@node-43-200 conf.d]#curl www.ab20.com
ab20.com
[root@node-43-200 conf.d]#curl www.ab10.com
ab10.com
[root@node-43-200 conf.d]#curl www.abc.com
abc.com

很多小的網站都是採用這種形式架構。只要花費很少申請個域名,主機有公網IP,把域名綁定在該主機上,就可以實現多個域名,虛擬主機的訪問。

4 網站身份驗證

httpd提供了基於IP地址驗證,用戶賬號密碼驗證等。接下來分別詳述用到的技術及實現方法。

4.1 htpassswd、Require指令

4.1.1 htpasswd指令

htpasswd用於爲指定用戶生成基於網頁用戶身份認證的密碼,由httpd-tools軟件包提供。支持3種加密算法:MD5、SHA和系統上的crypt()函數,不指定算法時,默認爲md5

[root@node-43-200 ~]#rpm -qf `which htpasswd`
httpd-tools-2.4.6-90.el7.centos.x86_64
htpasswd: illegal option -- h
Usage:
	htpasswd [-cimBdpsDv] [-C cost] passwordfile username
	htpasswd -b[cmBdpsDv] [-C cost] passwordfile username password
	htpasswd -n[imBdps] [-C cost] username
	htpasswd -nb[mBdps] [-C cost] username password
 -c  Create a new file.                                                                                       #創建一個新的文件
 -n  Don't update file; display results on stdout.                                                #不更新文件,將結果顯示爲標準輸出
 -b  Use the password from the command line rather than prompting for it.    #直接從命令行接受密碼,而不是根據提示輸入
 -i  Read password from stdin without verification (for script usage).               #從標準輸入讀取密碼,不再確認,主要用於腳本中
 -m  Force MD5 encryption of the password (default).                                     #使用MD5加密方式作爲默認
 -B  Force bcrypt encryption of the password (very secure).                            #強制使用bcrypy加密,這種很安全。
 -C  Set the computing time used for the bcrypt algorithm                               #設置bcrypt算法所用的時間(4-31),默認是5,越高越安全,消耗時間也越久.
     (higher is more secure but slower, default: 5, valid: 4 to 31).
 -d  Force CRYPT encryption of the password (8 chars max, insecure).         #強制使用CRYPT加密,最長8位字符,非安全
 -s  Force SHA encryption of the password (insecure).                                    #強制使用SHA算法加密,非安全
 -p  Do not encrypt the password (plaintext, insecure).                                    #不加密,使用明文,非安全
 -D  Delete the specified user.                                                                          #從密碼文件刪除指定的用戶
 -v  Verify password for the specified user.                                                       #驗證指定用戶的密碼

#------------舉例說明-----------------------------------------
#-n直接輸出,-b從命令行輸入密碼"centos",得到加密的字串。可以發現兩次加密後密文不同

[root@node-43-200 ~]#htpasswd -nb wang centos                                        
wang:$apr1$3nuRIEX6$exdqPP0B.h4H7l9CI96NO0
[root@node-43-200 ~]#htpasswd -nb wang centos
wang:$apr1$r97i60bL$AxJQuwepDbJ9mlo2v.Eoy.

#使用文件保存用戶名及密碼,初次使用-c 指定保存用戶、密碼的文件,後續增加不要用-c,否則會覆蓋以前的文件。

[root@node-43-200 ~]#htpasswd -cb pasfile wang centos
Adding password for user wang
[root@node-43-200 ~]#htpasswd -cmb pasfile songjia centos                      #-m使用MD5加密,首次需要-c創建文件。
Adding password for user songjia
[root@node-43-200 ~]#htpasswd -mb pasfile liuyan centos                          #第二次不要-c,否則會覆蓋。
Adding password for user liuyan
[root@node-43-200 ~]#htpasswd -sb pasfile yangying centos                       #-s指定加密方式sha算法,-b非交互,直接指定密碼
Adding password for user yangying
[root@node-43-200 ~]#cat pasfile 
songjia:$apr1$7cl.is/Y$Jz/cCAmhZKZ.xxJ5ASX0x.
liuyan:$apr1$dRPXqPrt$mWxmKCa.6fCUi43K.Mn/j.
yangying:{SHA}s6VCX366xaGxnQ00QYzgpPZKelE=

#密碼校驗,-v 指定密碼文件,指定用戶,輸入正確的密碼,會提示密碼正確與否。

[root@node-43-200 ~]#htpasswd -v pasfile yangying
Enter password: 
Password for user yangying correct.

#用戶刪除。-D 密碼文件 用戶。會發現直接就把用戶給刪除了。

[root@node-43-200 ~]#htpasswd -D pasfile yangying
Deleting password for user yangying
4.1.2 身份認證類基本指令

AuthType:指定web身份認證的類型。有效值爲none、basic、digest以及form。通常最基本的認證使用的是文件認證,所以通常使用basic。
AuthName:設置身份認證時的提示信息。
AuthUserFile file-path:指定web用戶認證列表。由htpasswd命令生成。
AuthGroupFile file-path:指定組認證文件,文件中分組格式爲"mygroup: Jim Bob Alice"。如果文件路徑爲相對路徑,則相對於ServerRoot
基於basic類型的認證就這麼幾個指令,最主要的還是require指令的使用。更多的認證方法見官方手冊的auth類模塊。

4.1.3 Require指令

該指令只能放在Directory容器中,用於控制對目錄的訪問權限。它的主要功能是由mod_authz_core模塊提供,但有些身份認證類模塊也提供它額外的功能,這時它可以放在< Directory >、< Files >或< Location >容器中。

  • Require all granted 允許所有人訪問

  • Require all denied 拒絕所有人訪問

  • Require env env-var [env-var] 符合給定的環境變量才能訪問。

  • Require method http-method [http-method] 符合給定的訪問方法纔可以訪問,比如get,post

  1. Require expr expression 符合特定的表達式的纔可以訪問

身份認證類模塊提供的require指令功能
mod_authz_user爲require
Require user userid [userid] …:認證列表中只有指定的userid才能訪問
Require valid-user:認證列表中的所有用戶都可以訪問
mod_authz_groupfile爲require指令提供的功能
Require group group1 [group2] …:指定組內的用戶都可以訪問
本地文件系統身份參考類
Require file-owner:要求web用戶名必須和請求文件的uid對應的username完全相同
Require file-group:要求web用戶名必須爲請求文件的gid組中的一員
mod_authz_host爲require指令提供的ip和host功能
Require ip 192.168.122.200 192.168.122.205 #特定IP
Require ip 192.168.122 10.10 #特定網段
Require host www.ruitais.com magedu.com #特定的域
Require local #你懂的
require後也可以跟not關鍵字,表示取反。
< RequireAll >:其內封裝的Require指令必須全都不能失敗,且至少有一個成功時,該容器成功。如果其內所有指令既不成功又不失敗,則該容器中立。其餘所有情況都會導致該容器失敗。
< RequireAny >:其內封裝的Require指令只要有一個成功,該容器就成功。如果其內所有指令既不成功又不失敗,則該容器中立。其餘所有情況(即全部失敗時)都會導致該容器失敗。
< RequireNone >:其內封裝的Require指令只要有一個成功時該容器就失敗,否則就中立。

4.2 web身份認證實現

basic認證方式:基於用戶、基於用戶組
1 使用htpasswd 建立用戶賬號密碼文件,放置www.abc.com 跟下,並重命名.htpwdfile(隱藏且禁止訪問)

[root@node-43-200 ~]#htpasswd -csb  pwdfile liuyan centos
Adding password for user liuyan
[root@node-43-200 ~]#htpasswd -sb  pwdfile songjia centos
Adding password for user songjia
[root@node-43-200 ~]#htpasswd -sb  pwdfile mayili centos
Adding password for user mayili
[root@node-43-200 ~]#htpasswd -mb  pwdfile jingtian centos
Adding password for user jingtian
[root@node-43-200 ~]#cat pwdfile 
liuyan:{SHA}s6VCX366xaGxnQ00QYzgpPZKelE=
songjia:{SHA}s6VCX366xaGxnQ00QYzgpPZKelE=
mayili:{SHA}s6VCX366xaGxnQ00QYzgpPZKelE=
jingtian:$apr1$lsoYdKzJ$MJc3No8AwrXmZ3cP2Dm25/

2 修改配置文件,假設只有虛擬www.abc.com主機要授權訪問,且只有songjia、liuyan可以訪問

[root@node-43-200 abc.com]#vim /etc/httpd/conf.d/vhost.conf
<virtualHost 192.168.122.200:80>
    ServerName www.abc.com
    DocumentRoot vhosts/abc.com
        AllowOverride Authconfig
        AuthType Basic
        AuthName "Are you roles,Input your Name"
        AuthUserFile "/etc/httpd/vhosts/abc.com/.htpwdfile"                   #此文件要用絕對路徑                                                        
        Require user songjia liuyan
    </Directory>
</virtualHost>

至此,基於用戶的授權訪問已經完成。
3 基於用戶組的授權訪問
增加組授權的文件

echo "allow:jingtian"> /etc/httpd/vhosts/abc.com/.ht_auth_group

修改配置文件。

vim  /etc/httpd/conf.d/vhost.conf
AuthGroupFile "/etc/httpd/vhosts/abc.com/.ht_auth_group"
Require group allow 

重啓服務,測試。可用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章