一、Apache概述安裝
1. 介紹
Apache HTTP Server(簡稱Apache)是Apache軟件基金會的一個開源的網頁服務器,是世界使用排名第一的Web服務器軟件。它可以運行在幾乎所有廣泛使用的計算機平台上,由於其跨平台和安全性被廣泛使用,是最流行的Web服務器端軟件之一。
apache的服務名稱是httpd
[apache官網](<https://apache.org/>)
[httpd2.4官方文檔](http://httpd.apache.org/docs/2.4/)
2. 安裝
[root@itcast ~]# yum -y install httpd
3. 快速入門
3.1 apache基本管理
# apache狀態管理
[root@itcast ~]# systemctl start|stop|restart|reload|status httpd.service
# 設置apache開機啟動
[root@itcast ~]# systemctl enable httpd.service
# 設置apache開機不啟動
[root@itcast ~]# systemctl disable httpd.service
3.2 站點根目錄
apache默認站點根目錄:var/www/html
3.3 apache服務目錄介紹
# /etc/httpd/
├── 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
├── logs -> ../../var/log/httpd # 日志目錄
├── modules -> ../../usr/lib64/httpd/modules # 模塊目錄
└── run -> /run/httpd # 運行時目錄
3.4 apache用戶
apache在安裝后會創建一個叫做apache的用戶, apache的子進程就是用這個用戶運行的
[root@itcast www]# tail -1 /etc/passwd
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
4.apache基本概念
4.1 apache進程
- apache默認監聽TCP協議的80端口
- apache默認會啟動一個主進程(控制進程)和多個子進程
查看apache相關進程:
[root@itcast html]# ps aux | grep httpd
其中root運行的是主進程,apache身份運行的是子進程,主進程的id保存在/etc/httpd/run/httpd.pid文件內。真正用來處理web請求的是子進程,主進程用來管理子進程。
4.2 apache模塊
- apache是一個模塊化設計的服務,核心只包含主要功能,擴展功能通過模塊實現(可擴展性強,各功能依賴性低)。不同模塊可以被靜態的編譯進程序,也可以動態加載。
- 模塊的動態加載通過DSO(Dynamic shared Object)實現。
查看模塊
[root@itcast html]# httpd -M
二、apache配置詳解及實踐
1、配置文件說明
1.1 主配置文件位置
/etc/httpd/conf/httpd.conf
1.2 配置文件格式
#directive(指令) value(值)
ServerRoot "/etc/httpd"
2、配置項詳解
2.1 ServerRoot
服務所在目錄的路徑,不需要做修改
ServerRoot "/etc/httpd"
2.2 Listen
監聽端口
#Listen 12.34.56.78:80
Listen 80
配置語法
Listen [IP-address:]portnumber [protocol]
實踐
# 1. 修改端口號
Listen 8080
# 2. Listen指令可重復出現多次
Listen 8080
Listen 80
# 注意:修改后必須重啟服務才可生效
[root@itcast conf]# systemctl restart httpd.service
2.3 Include
導入配置文件
Include conf.modules.d/*.conf
2.4 IncludeOptional
和include功能相同,都是導入配置文件的。區別是IncludeOptional導入的路徑有問題時會被忽略。不會報錯。
IncludeOptional conf.d/*.conf
2.5 User和Group
httpd服務子進程啟動時的賬號和組,這個不用修改
User apache
Group apache
2.6 ServerAdmin
服務運行時的管理員郵箱地址
ServerAdmin root@localhost
2.7 DocumentRoot
站點根目錄
DocumentRoot "/var/www/html"
語法
DocumentRoot directory-path
實踐
#DocumentRoot "/var/www/html"
DocumentRoot "/www"
#<Directory "/var/www/html">
<Directory "/www">
2.8 Directory
確定訪問目錄位置,標簽配置。標簽內是設置針對該目錄的訪問權限
<Directory "/var/www/html">
Options Indexes FollowSymLinks # 訪問時的展示形式,Indexes索引展示
AllowOverride None # 設置指令是否可以在.htaccess使用
Require all granted # 允許所有人訪問
</Directory>
-
Options 訪問時展示形式
Options Indexes 當前目錄下沒有默認頁面,就顯示目錄結構
Options FollowSymLinks 默認設置,允許訪問符號鏈接
Options None 關閉
-
AllowOverride
.htaccess
文件中允許的指令類型AllowOverride All 全部指令
AllowOverride None 默認值,不允許
AllowOverride directive-type [directive-type] … 具體指令類型
-
Require 訪問權限設置
Require all granted 無條件允許訪問
Require all denied 無條件拒絕訪問
Require method http-method [http-method] … 僅允許給定的HTTP方法訪問
Require ip 10 172.20 192.168.2 指定ip地址范圍的客戶端可以訪問
實踐
# 1. 去掉Indexes查看效果,注意改完配置后要重啟http服務
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
# 2. 去掉FollowSymLinks
<Directory "/var/www/html">
Options None
AllowOverride None
Require all granted
</Directory>
# 3. 使用Require
<Directory "/var/www/html">
Options None
AllowOverride None
Require all denied # 無條件拒絕訪問
</Directory>
<Directory "/var/www/html">
Options None
AllowOverride None
Require method POST # 僅允許post請求
</Directory>
2.9 IfModule
以特定模塊存在與否為條件的處理指令
# 如果dir_module存在,執行DirectoryIndex
<IfModule dir_module>
DirectoryIndex index.html # 站點默認展示頁
</IfModule>
語法
DirectoryIndex disabled | local-url [local-url] …
默認
DirectoryIndex index.html
實踐
# 在站點根目錄下創建一個index.html
[root@itcast html]# echo 'myindex' > index.html
2.10 Files
包含適用於匹配文件名的指令
<Files ".ht*">
Require all denied # 以.ht開頭的文件拒絕提供訪問
</Files>
2.11 ErrorLog
錯誤日志記錄位置
ErrorLog "logs/error_log"
2.12 LogLevel
錯誤日志記錄級別
LogLevel warn
錯誤級別選項
水平 | 描述 |
---|---|
emerg |
緊急情況 - 系統無法使用。 |
alert |
必須立即采取行動。 |
crit |
關鍵條件。 |
error |
錯誤條件。 |
warn |
警告條件。 |
notice |
正常但重要的情況。 |
info |
基本信息 |
debug |
調試級消息 |
2.13 IfModule log_config_module
訪問日志配置模塊
<IfModule log_config_module>
# 訪問日志3種格式: combined,common, combinedio
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>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
# 確定訪問日志位置和使用哪種日志格式
CustomLog "logs/access_log" combined
</IfModule>
日志格式說明
標識 | 含義 |
---|---|
%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”的值;即發出請求的應用程序; |
2.14 IfModule alias_module
文檔映射
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# Example:
# Redirect permanent /foo http://www.example.com/bar
# Alias: Maps web paths into filesystem paths and is used to
# Example:
# Alias /webpath /full/filesystem/path
# ScriptAlias: This controls which directories contain server scripts.
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" # cgi腳本映射
</IfModule>
Redirect 外部重定向
Alias 將url映射到文件系統個位置
ScriptAlias 將url映射到CGI腳本
2.15 AddDefaultCharset
響應內容的編碼格式
AddDefaultCharset UTF-8
三、虛擬主機配置
虛擬主機指的是在單一機器上運行多個網站.
虛擬主機可以“基於IP”,即每個 IP 一個站點; 或者“基於域名”, 即每個 IP 多個站點。這些站點運行在同一物理服務器上。
虛擬機配置語法
<VirtualHost addr[:port] [addr[:port]] ...>
serverName ...
DocumentRoot ...
...
</VirtualHost>
1、基於域名
# 實踐1,配置文件:/etc/httpd/conf.d/iplinux1.conf
<VirtualHost>
DocumentRoot "/var/www/iplinux1/"
ServerName www.iplinux1.org
ErrorLog "iplinux1-error_log"
TransferLog "iplinux1-access_log"
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
# 實踐2,配置文件:/etc/httpd/conf.d/iplinux2.conf
<VirtualHost>
DocumentRoot "/var/www/iplinux2/"
ServerName www.iplinux2.org
ErrorLog "ip2inux1-error_log"
TransferLog "ip2inux1-access_log"
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
2、基於ip
# 實踐1,配置文件:/etc/httpd/conf.d/iplinux1.conf
<VirtualHost 172.16.99.251>
DocumentRoot "/var/www/iplinux1/"
ServerName www.iplinux1.org
ErrorLog "iplinux1-error_log"
TransferLog "iplinux1-access_log"
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
# 實踐2,配置文件:/etc/httpd/conf.d/iplinux2.conf
<VirtualHost 172.16.99.252>
DocumentRoot "/var/www/iplinux2/"
ServerName www.iplinux2.org
ErrorLog "ip2inux1-error_log"
TransferLog "ip2inux1-access_log"
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
四、rewrite重寫
mod_rewrite
提供了基於正則表達式規則動態修改傳入的請求的 URL 的方法。可以定義任意的的url映射到內部的站點文件中
1演示現象,解決效果,得出rewrite概念
2-1如何實現具體講解步驟,可以帶入原理
2-2實踐
3剖析實現原理,提升知識面
4小結
1、rewrite需求
我們在使用Apache做為Web服務器時,有時候出於SEO優化或者是url路徑的簡潔,需要將輸入的url轉換成更為友好的url,這時候就可以使用rewrite重寫功能。
使用rewrite功能首先需要開啟mod_rewrite模塊。yum安裝的apache默認已經開啟。
2、rewrite使用詳解
rewrite規則可以在Directory指令中進行配置
rewrite學習的三個核心是RewriteEngine,RewriteCond,RewriteRule
2.1 RewriteEngine
rewrite功能的總開關,用來開啟rewrite重寫功能
RewriteEngine on
2.2 RewriteCond
RewriteCond定義規則條件,當請求滿足RewriteCond配置的條件時,執行RewriteCond后面的RewriteRule語句
比如:
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^Mozilla//5/.0.*
RewriteRule index index.html
上面的規則表示:如果匹配到http請求中HTTP_USER_AGENT是Mozilla//5/.0.*開頭的。訪問index時,會自動訪問到index.html
RewriteCond 和 RewriteRule 是上下對應的關系。可以有1個或者好幾個RewriteCond來匹配一個RewriteRule
**RewriteCond常見的HTTP請求匹配方式
RewriteCond %{HTTP_REFERER} (www.mytest.com)
RewriteCond %{HTTP_USER_AGENT} ^Mozilla//5/.0.*
RewriteCond %{REQUEST_FILENAME} !-f
HTTP_REFERER
判斷訪問者的來源
案例:
RewriteCond %{HTTP_REFERER} (www.mytest.com)
RewriteRule (.*)$ mytest.html
# 如果訪問的上一個頁面是www.mytest.com,無論當前訪問的是哪個頁面,都會跳轉到mytest.html
REQUEST_FILENAME
匹配當前訪問的文件
案例:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^news/sports/(\d+)\.html web/index\.php?c=news&a=sports&num=$1 [QSA,NC,L]
# 訪問news/sports/123.html,真實訪問的是web/index.php?c=news&a=sports&num=123
-f
是否是一個目錄,判斷是否不是一個目錄:!-d
-d
是否是一個文件,判斷是否不是一個問價:!-f
$1
表示第一個參數
2.3 RewriteRule
RewriteRule是配合RewriteCond一起使用的,RewriteRule是RewriteCond成功匹配后的具體執行過程
RewriteRule
的寫法:
RewriteRule Pattern Substitution [flags]
Pattern
是一個正則匹配
Substitution
匹配的替換內容
[flags]
參數限制
[QSA]
qsappend(追加查詢字符串)的意思,次標記強制重寫引擎在已有的替換字符串中追加一個查詢字符串,而不是簡單的替換。如果需要通過重寫規則在請求串中增加信息,就可以使用這個標記。
NC
nocase(忽略大小寫)的意思,它使Pattern忽略大小寫,也就是在Pattern與當前URL匹配時,"A-Z"和"a-z"沒有區別。這個一般也會加上,因為我們的url本身就不區分大小寫的。
Rredirect(強制重定向)的意思,適合匹配Patter后,Substitution是一個http地址url的情況,就調整出去了。
L
last(結尾規則)的意思,就是已經匹配到了,就立即停止,不再匹配下面的Rule了,類似於編程語言中的break
語法,跳出去了。
五、apache日志切割
1、為什么要進行日志切割
隨着網站訪問越來越大,web服務產生的日志文件也會越來越大,這個時候日志文件不僅占用了大量的服務器空間,而且日志分析也很麻煩
2、日志分割兩種方式
2.1 rotatelogs
rotatelogs是apache自帶的日志切割工具
案例:使用rotatelogs每天記錄一個日志文件
# 編輯httpd主配置文件 /etc/httpd/conf/httpd.conf
# 注釋下面兩行
ErrorLog "logs/error_log"
CustomLog "logs/access_log" combined
# 添加下面兩行
ErrorLog "|/usr/sbin/rotatelogs -l logs/error_%Y%m%d.log 86400"
CustomLog "|/usr/sbin/rotatelogs -l logs/access_%Y%m%d.log 86400" combined
說明:
86400為輪轉的時間,單位為秒
2.2 cronolog
Cronolog是一款日志輪循(rotation)工具,可以用它來把Apache、Tomcat等Web服務器上輸出的日志切分成按日或月保存的文件。
cronolog安裝
[root@ ~]# tar zxf cronolog-1.6.2.tar.gz
[root@ ~]# cd cronolog-1.6.2/
[root@ cronolog-1.6.2]# ./configure && make && make install
案例:使用cronologs每天記錄一個日志文件
ErrorLog "|/usr/local/sbin/cronolog logs/error-%Y%m%d.log"
CustomLog "|/usr/local/sbin/cronolog logs/access-%Y%m%d.log" combined
擴展:按小時輪詢生成日志
CustomLog "|/usr/local/sbin/cronolog logs /access_%Y%m%d%H.log" combined
3 總結
推薦使用cronolog,因為cronolog穩定高配置簡單。
六、apache防盜鏈
防盜鏈就是防止別人網站代碼里調用我們服務器的圖片、文件、視頻等資源。如果別人盜用我們的資源,會增加服務器的貸款壓力。
通過防盜鏈的方式,可以設置限制第三方的站點通過引用的方式獲取服務器上的圖片,如果想要獲取本站點的圖片數據,只能通過本站點訪問獲取,這樣也有效的減少了服務器的資源。
1、rewrite實現防盜鏈
1. RewriteEngine On
2. RewriteCond %{HTTP_REFERER} !^http://www.myitcast.com/.*$ [NC]
3. RewriteCond %{HTTP_REFERER} !^http://www.myitcast.com$ [NC]
4. RewriteCond %{HTTP_REFERER} !^http://myitcast.com/.*$ [NC]
5. RewriteCond %{HTTP_REFERER} !^http://myitcast.com$ [NC]
6. RewriteRule .*\.(gif|jpg|swf)$ http://www.myitcast.com/link.png [R,NC]
說明:
第1條:開啟rewrite重寫
第2~5條:開啟授信任的站點,能夠訪問站點的圖片資源
第6條:訪問站點的gif|jpg|swf等類型資源時,跳轉到
2、SetEnvIfNoCase
通過判斷瀏覽器頭信息來阻止盜鏈請求
SetEnvIfNoCase Referer "^$" local_ref
SetEnvIfNoCase Referer "www.benet.com/.*$" local_ref
SetEnvIfNoCase Referer "benet.com/.*$" local_ref
<filesmatch "\.(mp3|mp4|zip|rar|jpg|gif)">
Require all denied
Require env local_ref
</filesmatch>
說明:
SetEnvIfNoCase 當滿足某個條件時,為變量賦值,即根據客戶端請求屬性設置環境變量。
Referer :指明了請求當前資源原始資源的URL