41、apache用戶認證、域名跳轉、訪問日誌
- 1.對目錄加密
vim /usr/local/apache2.4/bin/apachectl start
vim /usr/local/apache2.4/conf/extra/httpd-vhosts.conf //把123.com那個虛擬主機編輯成如下內容
<VirtualHost *:80>
DocumentRoot "/data/wwwroot/www.123.com"
ServerName www.123.com
<Directory /data/wwwroot/123.com> //指定認證的目錄
AllowOverride AuthConfig //這個相當於打開認證的開關
AuthType Basic //認證的類型,一般為Basic
AuthUserFile /data/.htpasswd //指定密碼文件所在位置
require valid-user //指定需要認證的用戶為全部可用用戶
</Directory>
</VirtualHost> - 如下,在之前基礎上修改
<Directory /data/wwwroot/123.com> AllowOverride AuthConfig AuthName "123.com user auth" AuthType Basic AuthUserFile /data/.htpasswd require valid-user </Directory>
curl -x127.0.0.1:80 123.com
- 創建用戶密碼
/usr/local/apache2.4/bin/htpasswd -c -m /data/.htpasswd chinantfy
- 創建/data/.htpasswd 文件並建立用戶,密碼一md5加密,以後增加用戶時只需要-m選項即可
/usr/local/apache2.4/bin/apachectl -t /usr/local/apache2.4/bin/apachectl graceful
用瀏覽器登陸測試
curl -x127.0.0.1:80 www.123.com //狀態碼為401 curl -x127.0.0.1:80 -uaming:passwd www.123.com -I //狀態碼為200
- 2.對單一文件加密
將之前配置文件修改為<FilesMatch admin.php> AllowOverride AuthConfig AuthName "123.com user auth" AuthType Basic AuthUserFile /data/.htpasswd require valid-user </FilesMatch>
然後創建admin.php文件
vim /data/wwwroot/123.com/admin.php
<?php
echo "admin":
/usr/local/apache2.4/bin/apachectl -t
/usr/local/apache2.4/bin/apachectl graceful
用瀏覽器測試
二、域名跳轉
需求,把www.good.com域名跳轉到www.123.com,配置如下:
vim /usr/local/apache2.4/conf/extra/httpd-vhosts.conf
<VirtualHost :80>
DocumentRoot "/data/wwwroot/www.123.com"
ServerName www.123.com
ServerAlias 123.com www.good.com
<IfModule mod_rewrite.c> //需要mod_rewrite模塊支持
RewriteEngine on //打開rewrite功能
RewriteCond %{HTTP_HOST} !^www.123.com$ //定義rewrite的條件,主機名(域名)不是www.123.com滿足條件
RewriteRule ^/(.)$ http://www.123.com/$1 [R=301,L] //定義rewrite規則,當滿足上面的條件時,這條規則才會執行,301永久重定向,302臨時重定向,通常用301
</IfModule>
</VirtualHost>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.123.com$
RewriteRule ^/(.*)$ http://www.123.com/$1 [R=301,L]
</IfModule>
/usr/local/apache2/bin/apachectl -M|grep -i rewrite //若無該模塊,需要編輯配置文件httpd.conf,刪除rewrite_module (shared) 前面的#
/usr/local/apache2.4/bin/apachectl -t
/usr/local/apache2.4/bin/apachectl graceful
curl -x127.0.0.1:80 -I www.good.com //狀態碼為301
三、訪問日誌
訪問日誌記錄用戶的每一個請求
vim /usr/local/apache2.4/conf/httpd.conf //搜索LogFormat
可以看到log有兩種格式,之前默認是common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
把虛擬主機配置文件改成如下:
<VirtualHost *:80>
DocumentRoot "/data/wwwroot/www.123.com"
ServerName www.123.com
ServerAlias 123.com
CustomLog "logs/123.com-access_log" combined
</VirtualHost>
重新加載配置文件 -t,graceful
/usr/local/apache2.4/bin/apachectl -t
/usr/local/apache2.4/bin/apachectl graceful
41、apache用戶認證、域名跳轉、訪問日誌