Web Service

標(biāo)簽(空格分隔): Linux 運維 HTTP Web
實驗主機:
? CentOS7.2 10.0.0.11
? CentOS6.8 10.0.0.61


HTTP協(xié)議: Hyper Text Mark Language,超文本傳輸協(xié)議.客戶端/服務(wù)器端架構(gòu),服務(wù)器端監(jiān)聽在一個Socket(套接字)上,客戶端也是通過一個Scoket向服務(wù)端發(fā)送請求信息.

HTTP版本

? HTTP/0.9: 原型版本
? HTTP/1.0: 增加了cache,MIME等功能
? HTTP/1.1: 擴展了cache,加入更多的首部 條件式請求

端口范圍

IANA(The Internet Assigned Numbers Authority,互聯(lián)網(wǎng)數(shù)字分配機構(gòu))是負(fù)責(zé)協(xié)調(diào)一些使Internet正常運作的機構(gòu)。
常用端口分類:
? 0 ~ 1023: 眾所周知,永久地分配給固定的應(yīng)用程序使用,特權(quán)端口(僅root有權(quán)限使用)
? 1024 ~ 41951: 注冊端口,但要示略寬松,分配給某程序注冊使用.
? 40952+:客戶端程序使用的隨機端口,動態(tài)端口,或稱為私有端口.

Linux系統(tǒng)中的本地端口范圍查看可執(zhí)行cat /proc/sys/net/ipv4/ip_local_port_range命令查看,默認(rèn)是32768 ~ 61000,以下為這個文件的說明:
The /proc/sys/net/ipv4/ip_local_port_range defines the local port range that is used by TCP and UDP traffic to choose the local port. You will see in the parameters of this file two numbers: The first number is the first local port allowed for TCP and UDP traffic on the server, the second is the last local port number. For high-usage systems you may change its default parameters to 32768-61000 -first-last.

HTTP的事務(wù)與格式

HTTP的事務(wù)可分為request與response,即請求與響應(yīng).其格式分別如下
request:

<method> <URL><http version>
HEADERS:
<body>

response:

<http version> status code
<body>

URL: 定位互聯(lián)網(wǎng)中的某一個資源

<scheme>://<user>:<passowrd>@<host>[:<port>]/<path>;<params>?<query>#<frag>

method:
GET HEAD POST PUT DELETE OPTIONS RACE ...
status code

1xx:信息類
2xx:成功類
3xx:重定向類
4xx:客戶端錯誤類
5xx:服務(wù)端錯誤類

一次完整的Http請求響應(yīng)過程:
(1) 建立或處理連接;接收或拒絕請求;
(2) 接收請求
(3) 處理請求:解析請求;
(4) 訪問資源:
資源映射:DocumentRoot /var/www/html/
http://www.magedu.com/index.html --> /var/www/html/index.html
(5) 構(gòu)建響應(yīng)報文
(6) 發(fā)送響應(yīng)報文
(7) 記錄日志

HTTP協(xié)議的實現(xiàn)

  • httpd
  • nginx
  • ...

HTTP常用首部

? 通用首部

  • Connection: {close,keep-alive} 長連接
  • Date: 報文創(chuàng)建的日期時間
  • Via: 經(jīng)由,報文傳輸經(jīng)過的中間代理服務(wù)器
  • Cache-Control: 定義緩存控制機制,http1.1才有

? 請求首部(客戶端)

  • Accept: 可接受的MIME類型
  • Accept-language: 可接受的語言
  • Accept-encoding: 可接受的內(nèi)容編碼格式,如deflate,gzip
  • Accept-Charset: 可接受的字符集
  • Host: 請求的服務(wù)器的名稱和端口
  • Referer: 跳轉(zhuǎn)至當(dāng)前頁面的上級頁面
  • User-Agent: (多數(shù)情況下是)客戶端的瀏覽器類型
  • Expect:
  • If-Modified-Since
  • If-Unmodified-Since
  • If-None-Match
  • If-Match
  • Authorization:
  • Cookie

? 響應(yīng)首部

  • Age:
  • Server
  • Accept-Range: 服務(wù)端可接受的請求類型的范圍
  • Vary: 其它首部列表
  • Set-Cookie:

? 實體首部

  • Content-Encoding
  • Content-language
  • Content-Lenth
  • Content-location
  • Content-Type
  • Allow: 允許客戶端的請求方法
  • Location: 資源的真正地址
  • Etag
  • Expires
    • last-Modifiled

? 擴展首部

  • X-Forwarded-For

httpd的安裝與詳細(xì)說明

yum -y install httpd # 安裝httpd-2.4.6-45.el7.centos.x86_64
下面2個工具是作為依賴會被安裝
httpd-tools
mailcap.noarch
httpd的程序環(huán)境

`/etc/httpd/conf/httpd.conf`   # 主配置文件
`/etc/httpd/conf.d`            # 輔助配置文件目錄
`/etc/httpd/conf.modules.d`    # 加載模塊的配置文件

httpd的Unit File說明

[Unit]
Description=The Apache HTTP Server              # 描述
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd            # 給httpd設(shè)置額外的環(huán)境變量或傳遞額外的參數(shù),如下面的$OPTIONS就在這里設(shè)置
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND # 啟動httpd需要執(zhí)行的放在前臺交給systemd處理
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful # 重載時執(zhí)行的命令
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target

httpd相關(guān)的命令與用法

/usr/sbin/httpd:
    httpd: 不接任何參數(shù)直接啟動httpd
    -M: 列出httpd所有加載的靜態(tài)的與共享的模塊
    -t: 測試配置文件語法
    
/usr/sbin/apachectl: 管理httpd的一個shell腳本程序
    -k start:        開啟httpd
    -k stop:         關(guān)閉httpd
    -k restart:      重啟httpd
    -k  graceful:    優(yōu)雅地重啟httpd
    -k graceful-stop:優(yōu)雅地關(guān)閉httpd
  

httpd配置指令說明

ServerRoot "/etc/httpd"  # httpd服務(wù)器配置的目錄樹的頂級目錄,所有配置文件里的相對路徑都是相對這個
Listen 80                # 默認(rèn)httpd監(jiān)聽的IP與端口,可添加多個
KeepAlive On|Off         # 持久連接
KeepAliveTimeout NUM(ms) # 持久連接的超時時長
MaxKeepAliveRequests NUM # 一次持久連接允許的連接數(shù)目
LoadModule foo_module modules/mod_foo.so  # 加載指定模塊文件
Include conf.modules.d/*.conf             # 包含其它的配置子文件,相對于ServerRoot目錄
<IfModule [!]MODULE_NAME>:                # 指令塊,里面放置一些指令,但是只能是在指定的模塊存在時才有效
    "
    <IfModule dir_module>
        DirectoryIndex index.html   #定義站點主頁面,可跟多個
    </IfModule>
    "
ErrorLog "logs/error_log":          # 指定錯誤日志文件存放的位置
LogLevel warn            :          # 日志級別
LogFormat:                          # 日志格式,可查看[日志格式][1]
    
CustomLog "logs/access_log" common: # 自定義日志文件
DocumentRoot "/var/www/html":       # 網(wǎng)站文檔根目錄
ServerName www.example.com:80:      # 服務(wù)器名
<Directory "/usr/local/httpd/htdocs"> # 設(shè)置指令的生效(作用)范圍(本地文件系統(tǒng))其中常用的包含指令有
    Options Indexes FollowSymLinks None All ...
    AllowOverride None  # Types of directives that are allowed in .htaccess files
    # Allow open access:
    Require all granted|denied
    #Require [not] ip IP|NETWORK
    #Require [not] host HOSTNAME
<Location /private2/>                # 同上但基于URL路徑進行控制
Alias  /URL/  "/PATH/TO/SOME_DIR/"   # 路徑別名,URL-文件系統(tǒng)
<VirtualHost IP:PORT>                # 定義虛擬主機 本機的IP與監(jiān)聽的端口
    ServerName
    DocumentRoot
</VirtualHost>
<Location /status>                   # 定義狀態(tài)頁面,通常放在status.conf
    SetHandler server-status
    Require all granted
</Location>
    
ExtendedStatus {On|Off}              # 是否輸出擴展的狀態(tài)信息
------------------------------------------------------------------------------
httpd-2.2:static                    # MPM機制說明
httpd-2.4:shared
    prefork:兩級架構(gòu),由進程響應(yīng)每個請求
        master process:1個, 
        child process:n個,
    worker:每線程響應(yīng)一個請求;三級架構(gòu)
        master process:1個
        child process:n個
            thread:m個
    event:每進程響應(yīng)多個請求;
    
    prefork
        ServerLimit             
        StartServers
        MinspareServers
        MaxSpareServers
        MaxConnectionsPerchild
        MaxRequestWorkers 
        
    woker:
        ServerLimit
        StartServers
        MinSpareThreads
        MaxSpareThreads
        MaxRequestWorkers
        ThreadsPerChild 
        
    event:
        ThreadsPerChild
        MaxRequestWorkers
        AsyncRequestWorkerFactor
------------------------------------------------------------------------------      
AuthType basic                           # 用戶認(rèn)證
AuthName "Admin Area, Enter your name/password"
AuthUserFile "/etc/httpd/conf/.htpasswd" # htpasswd -c -m USERNAME [PWD]
Require valid-user
#AuthGroupFIle "/etc/httpd/conf/.htgroup"# 文件格式group_name: user1 user2 ..
#Require group 
------------------------------------------------------------------------------
使用mod_deflate模塊壓縮頁面優(yōu)化傳輸速度(需要裝載deflate_module模塊)
    適用場景:
        (1) 節(jié)約帶寬,但會額外消耗CPU;同時,可能有些較老瀏覽器不支持;
        (2) 壓縮適于壓縮的資源,例如文件文件/etc/httpd/conf.d/deflate.conf;
    SetOutputFilter DEFLATE
    # 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 \bMSI[E]  !no-gzip !gzip-only-text/html

httpd調(diào)用ssl實現(xiàn)HTTPS安全傳輸

SSL會話的簡化過程
    ㈠ 客戶端發(fā)送可供選擇的加密方式,并向服務(wù)器請求證書.
    ㈡ 服務(wù)器端發(fā)送證書以及選定的加密方式給客戶端
    ㈢ 客戶端取得證書并進行證書驗證
        ① 驗證證書的來源的合法性,用CA的公鑰解密證書上數(shù)字簽
        ② 驗證證書的內(nèi)容的合法性,完整性驗證
        ③ 檢查證書的有效期限
        ④ 檢查證書是否被吊銷 
        ⑤ 證書中擁有者的名字,與訪問的目標(biāo)主機要一對致
    ㈣ 客戶端端生成臨時會話密鑰(對稱密鑰),并使用服務(wù)器端的公鑰加密此數(shù)據(jù)發(fā)送給服務(wù)器,完成密鑰交換
    ㈤ 服務(wù)用此密鑰加密用戶請求的資源,響應(yīng)給客戶端
注意:SSL會話是基于IP地址創(chuàng)建,所以單IP主機止,僅可以使用一個https虛擬主機.

配置實例

1. 確保httpd裝載了ssl_module模塊,默認(rèn)不存在需要安裝.
`yum -y install mod_ssl`
/etc/httpd/conf.d/ssl.conf            # 配置基于SSL的虛擬主機
/etc/httpd/conf.modules.d/00-ssl.conf # 裝載mod_ssl.so模塊的指令
/usr/lib64/httpd/modules/mod_ssl.so   # mod_ssl.so的路徑
/usr/libexec/httpd-ssl-pass-dialog    # 
/var/cache/httpd/ssl                  # ssl緩存目錄,有效期為5分鐘
`systemctl reload httpd`              # 重載httpd使生效
2. 創(chuàng)建測試用的私有CA
    cd /etc/pki/CA/
    (umask 077;openssl genrsa -out private/cakey.pem 4096)
    openssl req -new -x509 -key private/cakey.pem -out cacert.pem
    echo 01 > serial
    touch index.txt
    
    cd /etc/httpd; mkdir certs;cd certs
    (umask 077;openssl genrsa -out httpd.key 2048)
    openssl req -new -key httpd.key -out httpd.csr  # 生成證書請求文件
    openssl ca -in httpd.csr -out httpd.crt
3. 編輯/etc/httpd/conf.d/ssl.conf 
    SSLCertificateFile /etc/httpd/certs/httpd.crt
    SSLCertificateKeyFile /etc/httpd/certs/httpd.key
    DocumentRoot "/var/www/html"
    ServerName www.magedu.com:443
4. systemctl httpd reload                           # 此時443端口應(yīng)該開啟了

httpd自帶的應(yīng)用程序

? htpasswd: basic認(rèn)證基于文件實現(xiàn),用于生成賬號和密碼的程序
? apachectl: httpd自帶的報務(wù)控制腳本,支持start和stop等命令
? apxs: apache 擴展工具
? rotatelogs:
? ab: apache benchmarking tools

httpd2.2與httpd2.4的不同之處

? 2.2中的"mpm_prefork_module (static)" 是靜態(tài)編譯的,可在/etc/sysconfig/httpd文件中更改,httpd的啟動腳本會調(diào)用這個環(huán)境文件

? 2.2的配置文件中MPM的默認(rèn)配置如下

<IfModule prefork.c>
    StartServers       8         # 初始啟動的子進程數(shù)量
    MinSpareServers    5         # 最小空閑子進程數(shù)量
    MaxSpareServers   20         # 最大空閑子進程數(shù)量
    ServerLimit      256         # 子進程數(shù)量上限
    MaxClients       256         # 最大并發(fā)請求數(shù) 其值小于等于ServerLimit
    MaxRequestsPerChild  4000    # 每個子進程服務(wù)請求超過4000的話就會被主進程銷毀重建
</IfModule>
    
<IfModule worker.c>
    StartServers         4       # 初始啟動的子進程數(shù)量 worker進程
    MaxClients         300       # 最大并請求數(shù)
    MinSpareThreads     25       # 最小空閑線程數(shù)量
    MaxSpareThreads     75       # 最大空閑線程數(shù)量
    ThreadsPerChild     25       #  每個worker有多少個線程,即啟動時有100個線程,但因為上面定義了最大空閑線程為75個所以會自動殺死一個worker子進程.(可實驗)
    MaxRequestsPerChild  0       # 每個worker進程最多能處理多少個請求.0表示沒有限制
</IfModule>

? 2.2中基于IP的訪問機制的指令與2.4不同,前者使用allow deny等詞,后者使用Require

Require all denied|granted       # httpd2.4中(將基于IP與基于用戶都用Require指令配置,統(tǒng)一了風(fēng)格)
Order allow,deny                 # httpd2.2中,由這2行設(shè)置
Allow from all

? 2.2中基于ServerName的虛擬主機,要使用專用指令NameVirtualHost

即在2.2中定義基于ServerName的虛擬主機的話必須在開件開頭添加一行如下:
NameVirtualHost IP:PORT
...
否則httpd會有如下錯誤提示:
[warn] _default_ VirtualHost overlap on port 80, the first has precedence

? 2.2中對于<Directory >授權(quán)沒有2.4嚴(yán)格,在2.4中必須對指定的文件做Directory授權(quán)才能訪問
[1]: http://httpd.apache.org/docs/2.4/mod/mod_log_config.html#formats

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容