1. 程式人生 > >Nginx服務企業應用

Nginx服務企業應用

out c-c 維護成本 系統環境 inux mongo 長大 標識 error

1.1 常用來提供靜態服務的軟件

Apache :這是中小型Web服務的主流,Web服務器中的老大哥,

Nginx :大型網站Web服務的主流,曾經Web服務器中的初生牛犢,現已長大。

Nginx 的分支 Tengine ( http://tengine.taobao.org/)目前也在飛速發展•

Lighttpd :這是一個不溫不火的優秀 Web軟件,社區不活躍,靜態解析效率很高.在 Nginx 流行前,它是大並發靜態業務的首選,國內百度貼吧、豆瓣等眾多網站都有Lighttpd奮鬥的身彩"

1.2 常用來提供動態服務的軟件

* PHP ( FastCGI ):大中小型網站都會使用,動態網頁語言PHP程序的解析容器。它可配合Apache解析動態程序,不過,這裏的PHP不是FastCGI守護進程橫式,而是mod_php5.so ( module)也可配合Nginx解析動態程序,此時的PHP常用FastCGI守護進程模式提供服務。

* Tomcat :中小企業動態Web服務主流,互聯網Java容器主流(如jsp、do )
* Resin :大型動態Web服務主流,互聯網Java容器主流(如jsp、do )
* IIS ( Internet information services ):微軟 windows 下的 Web 服務軟件(如 asp、aspx )

第2章 nginx 軟件

2.1 軟件介紹

如果你聽說或使用過 Apache軟件,那麽很快就會熟悉 Nginx軟件,與 Apache軟件類似, Nginx ( “engme x")是一個開源的,支持高性能、高並發的 WWW服務器和代理服務軟件。它是由俄羅斯人 Igor Sysoev開發的,最初被應用在勘羅斯的大型網站 www.rambler.ru 上,後來作者將源代碼以類BSD許可證的形式開源出來供全球使用。

Nginx因具有高並發(特別是靜態資源)占用系統資源少等特性,且功能豐富而逐漸流行起來。

在功能應用發面,Nginx不但是一個優秀的Web服務軟件,還具有反向代理負載均衡功能和緩存服務功能。在反向代理負載均衡功能方面,它類似於大名鼎鼎的LVS負載均衡及Haproxy等專業代理軟件,但是Nginx部署起來更為簡單、方便;在緩存服務功能方面,它又類似於Squid等專業的緩存服務軟件。

Nginx 可以運行在 UNIX、Linux、BSD、Mac 0S X、Solaris,以及 Microsoft Windows 等操作系統中。隨著Nginx在國內很多大型網站中的穩定高效運行,近兩年它也逐漸被越來越多的中小型網站所使用。當前流行的Nginx Web組合被稱為LNMP或LEMP(即Linux Nginx MySQL PHP),其中 LNMP 裏的 N 取自Nginx ( "engine x" )

Nginx 的官方介紹見 http://nginx.org/en

2.2 NGINX 軟件特性

2.2.1 HTTP服務器的特色及優點:

u 支持高並發:能支持幾萬並發連接(特別是靜態小文件業務環境)

u 資源消耗少:在3萬並發連接下,開啟10個Nginx線程消耗的內存不到200MB

u 可以做HTTP反向代理及加速緩存、即負載均衡功能,內置對RS節點服務器健康檢查功能,這相當於專業的Haproxy軟件或LVS的功能。

u 具備Squid等專業緩存軟件等的緩存功能。

u 支持異步網絡I/O事件橫型epoll(Linux2.6+)

2.2.2 nginx功能特性

  • web網站服務
  • 反向代理負載均衡(nginx /lvs /haproxy)
  • nginx緩存服務(memcache /redis /mongodb)

2.3 nginx軟件的企業功能應用

業務類型

應用方案

靜態業務

若是高並發場景,盡量采用Nginx或Lighttpd,二者首選Nginx

動態業務

理論上采用Nginx和Apache均可,建議選擇Nginx,為了避免相同業務的服務軟件多樣化,增加額外維護成本。動態業務可以由Nginx兼做前端代理,再根據頁面元素的類型或目錄,轉發到後端相應的服務器處理進程。

---首選tomcat

既有靜態業務又有動態業務

采用Nginx

利用nginx軟件是無法處理動態業務請求,要讓nginx結合php軟件處理動態業務請求,在加上mysql 即 LNMP架構

2.4 nginx軟件的動態訪問瓶頸

2.4.1 與其他軟件的對比

先來看看Apache軟件的特點,如下

² Apache2.2版本非常穩定強大,據官方說,Apache2.4版本性能更強。

² Prefork模式取消了進程創建開銷,性能很高。

² 處理動態業務數據時,因關聯到後端的引擎和數據庫,瓶頸不在Apache上。

² 高並發時消耗系統資源相對多一些。

² 基於傳統的select模型,高並發能力有限。

² 支持擴展庫,可通過DSO、apxs方法編譯安裝額外的插件功能,不需要重新編譯Apache

² 功能多,更穩定,更安全,插件也多。

² 市場份額在逐年遞減

再來看看Nginx軟件的特點,如下:

n 基於異步網結I/O模 型(epollk kqueue)

n 具備支持高性能,高並發的特性,並發連接可達數萬。

n 對小文件(小於1 MB的靜態文件)高並發支持很好,性能很高

n 不支持類似 Apache的DSO模式、擴展庫必須編譯進主程序(缺點)

n 進程占用系統資源比較低。

n 支持Web、反向Proxy、Cache三大重點功能,幷且都很優秀。

n 市場份額在逐年快速增加。

最後是Lighttpd的特點,如下:

² 基於異步網絡 I/ O模型,性能、並發都與 Nginx相近。

² 擴展庫是 SO模式,比Nginx靈活

² 目前國內的使用率比較低,安全性沒有 Apache和Nginx好。

² 通過插件(mod_secdownload)可實現文件 URL地址加密(優點)

² 社區不活躍,市場份額較低,

2.4.2 最主要的區別(select & epoll)

NGINX 使用的是epoll 和Kqueue 異步網絡I/O模型,而apache使用的是傳統的select模型

比喻:

第一個比喻:

假設你在大學讀書,住的宿舍樓有很多房間,你的朋友要來找你。select版宿管大媽就會帶著你的朋友到各房間挨個去找,直到找到你為止。而epoll版宿管大媽會先記下每位入住同學的房間號,你的朋友來找你時,只需告訴你的朋友你住在哪個房間即可,不用親自帶著你的朋友滿宿舍樓找人了。如果同時來了100個人,都要找自己住這棟樓的同學,select版和epoll版宿管大媽,誰的效率更高,就很明顯了。

第二個比喻:

select的調用復雜度是線性的,即O(n)。舉個例子,一個保姆照看照看一群孩子,如果把孩子是否需要尿尿比作網絡I/O事件,select的作用就好比這個保姆挨個詢問每個孩子"你要尿尿嗎?”如果孩子回答是,保姆則把孩子領出來放到另外一個地方。當所有孩子詢問完之後,保姆領著這些要尿尿的孩子去上廁所(處理網絡I/O事件).在epoll機制下,保姆不再需要挨個詢問每個孩子是否需要尿尿。取而代之的是,如果孩子需要尿尿,他就自己主動站到事先約定好的地方,而保姆的職責就是查看事先約定好的地方是否有孩子。如果有小孩,則領著孩子去上廁所(網絡事件處理)。因此,epoll的這種機制,能夠高效地處理成千上萬的並發連接,並且性能不會隨著連接數増加而下降太多。

2.4.3 apache select和nginx epoll技術對比圖

指標

select

epoll

性能

隨著連接數的增加性能急劇下降。處理成千上萬的並發連接數,性能很差

隨著連接數的增加,性能基本上沒有下降。處理成千上萬連接時性能很好

連接數

連接數有限制,處理的最大連接數不超過1024,如果要處理的連接數超過1024個,則需要修改FD_SETSIZE宏,並重新編譯

連接數無限制

內在處理機制

線性輪詢

回調callback

開發復雜性

第3章 nginx的安裝與使用

3.1 nginx軟件的編譯安裝步驟

3.1.1 檢查軟件安裝的系統環境

[root@web01 ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[root@web01 ~]# uname -r
2.6.32-696.el6.x86_64

3.1.2 安裝nginx的依賴包(pcre-devel openssl-devel)

yum install -y pcre-devel openssl-devel

pcre:兼容perl語言正則表達式,perl compatible regular expressions

rewirte模塊 參數信息(perl方式定義正則表達式)

openssl:ssh---openssh/openssl---https

總結:所有安裝依賴軟件,後面都要加上-devel

3.1.3 下載nginx軟件

wget http://nginx.org/download/nginx-1.10.2.tar.gz

說明:軟件很小,用心查看一下

解壓軟件

tar xf nginx-1.10.2.tar.gz

3.1.4 創建管理用戶 www

useradd -M -s /sbin/nologin www

3.1.5 nginx軟件編譯安裝過程

3.1.5.1 註意

軟件編譯安裝步驟

a>軟件解壓配置(將軟件程序安裝到哪個目錄中 開啟nginx軟件的哪些功能)

b>軟件編譯過程

c>軟件編譯安裝過程

註意順序,順序不對軟件安裝會出錯

3.1.5.2 編譯安裝軟件

1、配置軟件,在軟件的解壓目錄中

[root@web01 nginx-1.10.2]# ./configure --prefix=/application/nginx-1.10.2 --user=www --group=www --with-http_stub_status_module --with-http_ssl_module

編譯參數說明:

--prefix 表示指定軟件安裝到哪個目錄中,指定目錄不存在會自動創建

--user/--group nginx工作進程由哪個用戶運行管理

--with-http_stub_status_module 啟動nginx狀態模塊功能(用戶訪問nginx的網絡信息)

--with-http_ssl_module 啟動https功能模塊

通過軟件編譯過程中的返回值是否正確,確認配置是否正確

[root@web01 nginx-1.10.2]# echo $?
0

2、編譯軟件

[root@web01 nginx-1.10.2]# make

3、編譯安裝

[root@web01 nginx-1.10.2]# make install

3.1.6 創建軟連接

[root@web01 application]# ln -s /application/nginx-1.10.2/ /application/nginx

3.1.7 精簡化nginx.conf 主配置文件內容

[root@web01 conf]# egrep -v "#|^$" nginx.conf.default >nginx.conf

3.1.8 啟動程序

[root@web01 application]# /application/nginx/sbin/nginx
[root@web01 application]#

檢查是否啟動

[root@web01 application]# ps -ef |grep nginx
root      26548      1  0 20:13 ?        00:00:00 nginx: master process /application/nginx/sbin/nginx
www       26549  26548  0 20:13 ?        00:00:00 nginx: worker process       
root      26551  23431  3 20:13 pts/0    00:00:00 grep --color=auto nginx

檢查端口信息

[root@web01 application]# netstat -lntup |grep 80
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      26548/nginx 

服務部署完成

至此軟件安裝完畢!

nginx命令簡化方法

echo ‘export PATH=/application/nginx/sbin:$PATH‘>>/etc/profile
source /etc/profile
which nginx

3.1 nginx 目錄結構

[root@web01 nginx]# ll
total 36
drwxr-xr-x 2 root root 4096 Oct 21 19:34 conf    #配置文件保存目錄
drwxr-xr-x 2 root root 4096 Oct 21 19:34 html    #站點目錄
drwxr-xr-x 2 root root 4096 Oct 21 20:26 logs    #nginx 服務相關日誌文件保存目錄(錯誤日誌訪問日誌)
drwxr-xr-x 2 root root 4096 Oct 21 19:34 sbin    # 服務命令目錄(只有一個nginx文件)

3.2 nginx.conf 配置文件說明

這樣的配置文件是通過精簡化配置文件得到!

[root@web01 conf]# cat nginx.conf
worker_processes  1;                        ← worker 進程數量
events {                                    ←事件區塊
    worker_connections  1024;               ←每個worker進程可以處理的連接數
}                                            ←事件區塊結束
http {                                      ← HTTP 區塊
    include       mime.types;               ←支持的媒體文件
    default_type  application/octet-stream;←默認的媒體類型
    sendfile        on;                     ←高效傳輸模式
    keepalive_timeout  65;                  ←超時時間
    server {                                 ← server 區塊
        listen       80;                    ←端口
        server_name  localhost;             ←域名
        location / {                        ←第一個location區塊
            root   html;                     ←站點目錄
            index  index.html index.htm;     ←首頁文件
        }                                    ←第一個location區塊結束
        error_page   500 502 503 504  /50x.html;  ← 錯誤信息配置
        location = /50x.html {                  文件位置
            root   html;                      在哪找:路徑
        }                                     
    }                                         ← server 區塊結束
}                                            ← HTTP 區塊結束

3.2.1 站點目錄與首頁文件概

3.2.2 配置文件詳解

3.3 【常見錯誤】nginx軟件的編譯安裝常見錯誤說明

3.3.1 nginx軟件安裝過程中遇到的問題

軟件依賴包未正確安裝問題---PCRE依賴包沒有安裝

./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

解決方法:yum install pcre pcre-devel -y

軟件依賴包未正確安裝問題---OPENSSL依賴包沒有安裝

./configure: error: SSL modules require the OpenSSL library.
You can either do not enable the modules, or install the OpenSSL library
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl=<path> option.

解決方法:yum install openssl openssl-devel -y

3.3.2 nginx軟件啟動過程中遇到的問題

nginx軟件重復啟動產生的錯誤信息

[root@web01 nginx-1.10.2]# /application/nginx/sbin/nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

解決方法:

nginx軟件已經啟動無需反復啟動,如果需要重新啟動需要停止nginx進程或者用reload方式進行重啟

3.3.3 啟動 Nginx 時如下報錯"nginx:[emerg]getpwnam(“nginx”〉failed"

解答這是因為沒有對應的Nginx服務用戶,執行useradd nginx-s/sbin/no丨ogin-M創建 Nginx

用戶即可。為了讓讀者理解問題,重現上述錯誤過程,命令如下:

[root@web01 tools]# pkill nginx
[root@web01 tools]# userdel nginx
[root@web01 tools]# /application/nginx/sbin/nginx
nginx: [emerg] getpwnam(Mnginx") failed
[root@web01 tools]# useradd nginx -s /sbin/nologin -M
[root@web01 tools]# /application/nginx/sbin/nginx

3.3.4 編譯安裝pcre編譯軟件時,gcc不全導致報錯(本文使用yum安裝不存在此問題)。

報錯信息如下:

[root@gjlin2 pcre-8.30]# make && make install
make all-am
make[l] : Entering directory 7home/gjlin/tools/pcre-8.30‘
CXX pcrecpp.lo
libtool : compile : unrecognized option ‘-DHAVE_CONFIG_H‘
libtool : compile : Try ‘libtool --help* for more information.
make[l】:*** [pcrecpp.lo】錯誤 1
make[l] : Leaving directory Vhome/gjlin/tools/pcre-8.30‘
make : *** [all]錯誤 

解答:執行“yum -y install gcc-c++”命令安裝gcc-c++依賴包。

3.3.5 nginx軟件編譯安裝後,看不到程序目錄(/application)

說明:編譯安裝步驟不對(配置 編譯 編譯安裝生成/appliation)

3.3.6 nginx軟件排查問題三部曲說明

a 在客戶端上ping服務器端IP,檢查鏈路是否通暢

b 在客戶端上telnet服務器端IP、端口,檢查鏈路訪問是否通暢

c 在客戶端上wget檢測模擬頁面訪問是否正常

3.3.7 【註意】403狀態碼出現情況原因

01. 服務阻止客戶端訪問

02. 服務端站點目錄中,沒有指定首頁文件信息

3.4 nginx軟件使用命令參數

3.4.1 nginx 啟動方法

[root@web01 application]# /application/nginx/sbin/nginx

3.4.2 nginx 停止方法

[root@web01 application]# /application/nginx/sbin/nginx -s stop

3.4.3 nginx 重啟方法 (平滑重啟)

[root@web01 application]# /application/nginx/sbin/nginx -s reload

3.4.4 檢查配置文件語法是否正確

[root@web01 application]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful

3.4.5 顯示配置參數 -V (大寫V)

[root@web01 application]# /application/nginx/sbin/nginx -V
nginx version: nginx/1.10.2
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/application/nginx-1.10.2 --user=www --group=www --with-http_stub_status_module --with-http_ssl_module

3.4.6 nginx軟件使用過程中深入說明

①. nginx軟件語法檢查方法:

    nginx -t 

②. nginx軟件訪問測試過程:

curl -v www.baidu.com

③. nginx軟件編譯參數查看:

    nginx -V                 <--- 查看原有的編譯參數信息

3.5 nginx軟件靜態頁面編寫過程

編寫配置文件

[root@web02 www]# cat ../../conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name www.zinx.top;
        location / {
            root   html/www;
            index  clsn.html index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

編寫靜態訪問頁面文件信息

[root@web1 www]# cat clsn.html  
<html>
<meta charset="utf-8">
<head>
<title>TEST</title>
</head>
<body>
慘綠少年
<table border=1>
<tr> <td>01</td> <td> </td> </tr>
<tr> <td>02</td> <td> </td> </tr>
 <tr> <td>03</td> <td> </td> </tr>
 </table>
<a href="http://blog.znix.top">
<img src="znix.png" />
</a>
</body>
</html>

第4章 nginx進階 --虛擬主機配置

4.1 【企業要求】需要按照以前nginx服務編譯安裝過程安裝

1、參看已安裝服務的配置參數信息

[root@web01 sbin]# /application/nginx/sbin/nginx -V
nginx version: nginx/1.10.2
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/application/nginx-1.10.2 --user=www --group=www --with-http_stub_status_module --with-http_ssl_module

-V 參數能顯示軟件的詳細詳細,安裝配置參數

2、按照配置參數進行部署

4.1.1 【語法檢查】檢查配置文件

[root@web01 nginx]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful

4.2 首頁文件不存在--利用nginx服務搭建文件共享服務器

通過配置 autoindex on; 參數

使用 autoindex參數,nginx能識別的直接顯示,不識別的直接下載

配置完 autoindex on; 參數以後 會顯示站點下的文件信息

對於nginx可以解析的資源會解析相應的內容

對於nginx不可以解析的資源會直接下載

4.2.1 進行curl時,報403錯誤,因為沒有首頁文件信息

 [root@web02 ~]# echo ‘web01 www‘ > /application/nginx/html/www/index.html

<- 在虛擬主機指定的站點目錄中創建首頁文件

[root@web02 ~]# curl www.nmtui.com
<- 利用curl命令本地檢測nginx配置是否成功;已經存在首頁文件,測試成功

4.2.2 autoindex on參數實踐

1)修改配置文件

[root@web01 www]# cat ../../conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       10.0.0.8:80;
        server_name  www.nmtui.com;
        location / {
            root   html/www;
            autoindex on;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2)重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful
[root@web01 conf]# /application/nginx/sbin/nginx -s reload

3)訪問測試

4.3 【概念】虛擬主機的概念和類型

虛擬主機使用的是特殊的軟硬件技術,它把一臺運行在因特網上的服務器主機分成一臺臺“虛擬”的主機,每臺虛擬主機都可以是一個獨立的網站,可以具有獨立的域名,具有完整的Intemet服務器功能(WWW、FTP、Email等),同一臺主機上的虛擬主機之間是完全獨立的。從網站訪問者來看,每一臺虛擬主機和一臺獨立的主機完全一樣。

利用虛擬主機,不用為每個要運行的網站提供一臺單獨的Nginx服務器或單獨運行一組Nginx進程。虛擬主機提供了在同一臺服務器、同一組Nginx進程上運行多個網站的功能。

4.3.1 虛擬主機概念

所謂虛擬主機,在Web服務裏就是一個獨立的網站站點,這個站點對應獨立的域名(也可能是ip或端口.具有獨立的程序及資源目錄,可以獨立地對外提供服務供用戶訪問。

這個獨立的站點在配置裏是由一定格式的標簽段標記的,對於Apache軟件來說,一個虛擬主機的標簽段通常被包含在以的此<VirtualHost></VirtualHost>,而Nginx軟件則使用一個server{}標簽來標示一個虛擬主機。一個Web服務裏可以有多個虛擬主機標簽對,即可以同時支持多個虛擬主機站點。

4.3.2 虛擬主機類型

常見的虛擬主機類型有如下幾種

1)基於域名的虛擬主機

所謂基於域名的虛擬主機,意思就是通過不同的域名區分不同的虛擬主機,基於域名的虛擬主機是企業應用最廣的虛擬主機類型,幾乎所有對外提供服務的網站使用的都是基於域名的虛擬主機,例如: www.znix.top。

2)基於端口的虛擬主機

同理,所謂基於端口的虛擬主機,意思就是通過不同的端口來區分不同的虛擬主機,此類虛擬主機對應的企業應用主要為公司內部網站,例如:一些不希望直接對外提供用戶訪問的網站後臺等,訪問基於端口的虛擬主機,地址裏要帶有端口,例如:http://blog.znix.top:80

3)基於IP的虛擬主機

所謂基於IP的虛擬主機,意思是通過不同的IP區分不同的虛擬主機,

4.3.3 Nginx配置虛擬主機的步驟如下(適合各類虛擬主機類型)

1)增加一個完整的server標簽段到結尾處。註意,要放在http的結束大括號前,也就是將server標簽段放入http標簽。

2)更改server_name及對應網頁的root根目錄,如果需要其他參數,可以增加或修改。

3)創建Seever_name域名對應網頁的根目錄,並且建立測試文件,如果沒有index首頁,訪問會出現403錯誤。

如果是apache軟件,沒有首頁文件,默認會把站點目錄下面的信息顯示出來

nginx出403錯誤解決方式:http://clsn.blog.51cto.com/2561410/1633952

autoindex on;#<==當找不到首頁文件時,會展示目錄結構,這個功能一般不要用除非有需求。

PS:顯示的目錄結構中,有些信息點擊就是下載,有的點擊就是顯示,因為擴展名稱不一樣

根本在於nginx軟件是否能夠進行解析

nginx是否解析:

1.htmljpg認識顯示出內容

2.不認識不解析便直接下載

4)檢査Nginx配置文件語法,平滑重啟Nginx服務,快速檢査啟動結果。

5)在客戶端對server_name處配置的域名做host解析或DNS配置,並檢査(ping域名看返回的IP是否正確)。

6)在Win32瀏覽器中輸入地址訪問,或者在Linux客戶端做hosts解析,用wget或curl接地址訪問。

7)在服務重啟或關閉之前先進行一次配置文件檢查 /application/ngnix/sbin/nginx -t

Nginx虛擬主機的官方幫助網址為:http://Nginx.org/en/docs/http/requestj3rocessing.html

4.4 【實踐】虛擬主機配置

4.4.1 基於域名的虛擬主機

修改配置文件

[root@web01 ~]# cat  /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  www.nmtui.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    server {
        listen       80;
        server_name  bbs.nmtui.com;
        location / {
            root   html/bbs;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    server {
        listen       80;
        server_name  blog.nmtui.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

檢查配置信息是否正確

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful

重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -s reload

註意:服務沒有啟動的時候不能使用平滑重啟

創建站點目錄

[root@web01 conf]# for name in www blog bbs ;do  mkdir ../html/$name -p ;done

創建主頁文件

[root@web01 conf]# for name in www blog bbs ;do echo "web01 $name" >../html/$name/index.html  ;done

檢查主頁內容信息

[root@web01 conf]# for name in www blog bbs ;do  cat ../html/$name/index.html ;done
web01 www
web01 blog
web01 bbs

修改主機hosts文件

[root@web01 ~]# vim /etc/hosts
172.16.1.8    web01 www.nmtui.com blog.nmtui.com bbs.nmtui.com

測試

[root@web01 ~]# curl  www.nmtui.com
web01 www
[root@web01 ~]# curl  blog.nmtui.com
web01 blog
[root@web01 ~]# curl  bbs.nmtui.com
web01 bbs

4.4.2 基於端口的虛擬主機

修改配置文件內容

[root@web01 conf]# vim nginx.conf
    server {
        listen       81;
        server_name  bbs.nmtui.com;
        location / {
            root   html/bbs;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
"nginx.conf" 46L, 1098C written  

重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful
[root@web01 conf]# /application/nginx/sbin/nginx -s reload

檢查端口信息

[root@web01 conf]# netstat -lntup |grep ng
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      40110/nginx        
tcp        0      0 0.0.0.0:81                  0.0.0.0:*                   LISTEN      40110/nginx  

測試訪問

[root@web01 ~]# curl  bbs.nmtui.com:81
web01 bbs

4.4.3 基於IP的虛擬主機

註意:

采用基於IP的虛擬主機,配置文件修改後要重啟(-s stop)

配置和IP地址配置相關的都要采用(-s stop)重啟,不能夠使用軟重啟的方式

修改配置文件

[root@web01 conf]# cat nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       10.0.0.8:80;
        server_name  www.nmtui.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

檢查配置文件格式

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful

重啟服務,註意使用的是直接重啟的方式

只要nginx配置文件中涉及到IP地址的更改只能正真的重啟才生效

[root@web01 conf]# /application/nginx/sbin/nginx -s stop
[root@web01 conf]# /application/nginx/sbin/nginx
[root@web01 conf]# netstat -lntup |grep ng
tcp        0      0 10.0.0.8:80                 0.0.0.0:*                   LISTEN      40592/nginx   

訪問測試

4.5 【規範化配置】nginx配置文件企業規範化

4.5.1 第一個裏程碑: 創建虛擬主機配置文件存儲目錄

[root@web01 conf]# pwd
/application/nginx/conf
[root@web01 conf]# mkdir extra

4.5.2 第二個裏程碑: 生產虛擬主機配置文件

[root@web01 conf]# sed -n ‘10,21p‘ nginx.conf > extra/www.conf
[root@web01 conf]# sed -n ‘22,33p‘ nginx.conf > extra/bbs.conf
[root@web01 conf]# sed -n ‘34,45p‘ nginx.conf > extra/blog.conf

4.5.3 第三個裏程碑: 修改nginx配置文件使之加載識別虛擬主機配置文件

[root@web01 conf]# cat  nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    include extra/*;
}

4.5.4 重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful

4.5.5 檢查監聽端口

[root@web01 conf]# netstat -lntup |grep ng
tcp        0      0 0.0.0.0:80           0.0.0.0:*       LISTEN      40714/nginx       

4.5.6 查看配置文件的加載順序

[root@web01 logs]# /application/nginx/sbin/nginx -T

參數說明:

-T : test configuration, dump it and exit

測試配置文件,並且加載一遍,並顯示加載的順序

4.5.7 【優化】調整 inculde的加載順序,指定第一個加載為conf

[root@web01 conf]# vim nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    include extra/www.conf;
    include extra/bbs.conf;
    include extra/blog.conf;
}

4.5.8 重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful
[root@web01 conf]# /application/nginx/sbin/nginx -s reload

4.5.9 說明;

這樣的配置能夠讓用戶通過IP訪問的時候,訪問到的網站是www的網站。

4.6 別名的配置

在配置文件中添加別名

[root@web01 conf]# vim extra/www.conf
    server {
        listen       80;
        server_name  www.nmtui.com nmtui.cn;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -s reload

修改hosts 進行訪問測試

[root@web01 www]# curl  nmtui.cn
web01 www

4.7 status 狀態模塊

4.7.1 狀態模塊的配置

修改配置文件,添加三status模塊

[root@web01 conf]# vim nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
          server{
          listen  80;
          server_name  status.nmtui.com;
          location / {
            stub_status on;
            access_log   off;
          }
        }
    include extra/www.conf;
    include extra/bbs.conf;
    include extra/blog.conf;
}

檢查配置文件是否正確

[root@web01 conf]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful

重啟服務

[root@web01 conf]# /application/nginx/sbin/nginx -s reload

訪問測試

說明:

以上頁面內容信息主要會被zabbix監控服務調取,形成圖像信息
根據圖形信息,從而判斷nginx網站服務用戶訪問量情況

4.7.2 狀態模塊說明

參數

參數說明

Active connections

當前的活動客戶端連接數量

accepts

接受客戶端連接的總數

handled

處理的連接總數

requests

客戶端請求的總數

Reading

nginx正在讀請求頭的當前連接數。

Writing

nginx正在將響應寫回客戶端的當前連接數。

Waiting

當前空閑客戶端連接數等待一個請求。

4.8 nginx的日誌功能

nginx的兩種日誌種類

錯誤日誌:記錄nginx運行錯誤情況信息

訪問日誌:記錄用戶訪問日誌信息

官方說明: http://nginx.org/en/docs/ngx_core_module.html#error_log

4.8.1 定義錯誤日誌信息

系統默認配置

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

配置錯誤日誌,修改主配置文件

[root@web01 logs]# vim ../conf/nginx.conf
worker_processes  1;
error_log  logs/error.log  error;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
          server{
          listen  80;
          server_name  status.nmtui.com;
          location / {
            stub_status on;
            access_log   off;
          }
        }
    include extra/www.conf;
    include extra/bbs.conf;
    include extra/blog.conf;
}

重啟服務

[root@web01 logs]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful
[root@web01 logs]# /application/nginx/sbin/nginx -s reload

查看錯誤日誌信息

[root@web01 logs]# tail  error.log
2017/10/25 11:41:55 [error] 40842#0: *7 open() "/application/nginx-1.10.2/html/www/favicon.ico" failed (2: No such file or directory), client: 10.0.0.1, server: www.nmtui.com, request: "GET /favicon.ico HTTP/1.1", host: "www.nmtui.com", referrer: "http://www.nmtui.com/"

4.8.2 訪問日誌配置

系統默認配置

#log_format  main  ‘$remote_addr - $remote_user [$time_local] "$request" ‘
#                  ‘$status $body_bytes_sent "$http_referer" ‘
#                  ‘"$http_user_agent" "$http_x_forwarded_for"‘;
 
#access_log  logs/access.log  main;

修改訪問日誌配置--修改主配置文件

[root@web01 www]# cat ../../conf/nginx.conf
worker_processes  1;
error_log  logs/error.log  error;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    log_format  main  ‘$remote_addr - $remote_user [$time_local] "$request" ‘
                  ‘$status $body_bytes_sent "$http_referer" ‘
                  ‘"$http_user_agent" "$http_x_forwarded_for"‘;
 
          server{
          listen  80;
          server_name  status.nmtui.com;
          location / {
            stub_status on;
            access_log   off;
          }
        }
    include extra/www.conf;
    include extra/bbs.conf;
    include extra/blog.conf;
}

修改訪問日誌配置--修改虛擬主機配置文件

[root@web01 www]# cat /application/nginx/conf/extra/www.conf
    server {
        listen       80;
        server_name  www.nmtui.com nmtui.cn;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
     access_log  logs/access_www.log  main;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

4.8.3 【重要】訪問日誌信息說明

日誌內容

10.0.0.1 - - [22/Oct/2017:16:04:54 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" "-"

配置文件

‘$remote_addr - $remote_user [$time_local] "$request" ‘
‘$status $body_bytes_sent "$http_referer" ‘
‘"$http_user_agent" "$http_x_forwarded_for"‘;

日誌信息說明

參數

日誌內容

含義

$remote_addr

10.0.0.1

客戶端ip地址

-

-

$remote_user

-

顯示遠程訪問者用戶信息

[$time_local]

[22/Oct/2017:16:04:54 +0800]

顯示訪問時間

$request

GET / HTTP/1.1"

請求行信息

$status

304

狀態碼

$body_bytes_sent

0

響應報文主體內容大小

$http_referer

-

$http_user_agent

Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36

客戶端瀏覽網頁工具信息

$http_x_forwarded_for

-

反向代理轉發

詳細日誌詳細說明

Nginx日誌變量

說明

$remote_addr

記錄訪問網站的客戶端地址;即源IP地址

$http_x_forwarded_for

當前端有代理服務器時,設置web節點記錄客戶端地址的配置,此參數生效的

前提是代理服務器上也進行了相關的x_forwarded_for設置

可以記錄用戶真實的IP地址信息

$remote_user

遠程客戶端用戶名稱

$time_local

記錄訪問時間與時區

$request

用戶的http請求起始行信息

$status

http狀態碼,記錄請求返回的狀態,例如:200 , 404 , 301等

$body_bytes_sents

服務器發送給客戶端的響應body字節數

$http_referer

記錄此次請求是從哪個鏈接訪問過來的,可以根據referer進行防盜鏈設置

即表示是哪個網站介紹過來的

$http_user_agent

記錄客戶端訪問信息,例如:瀏覽器、手機客戶端等

在沒有特殊要求的情況下,采用默認的配置即可,更多可以設置的記錄日誌信息的變量見:http://nginx.org/en/docs/http/ngx_httpJog_module.html1

4.8.4 日誌的切割

切割日誌方式

01:利用腳本實現日誌切割

簡單腳本

[root@web01 logs]# cat /server/scripts/log_cut.sh
#!/bin/bash
 
mv /application/nginx/logs/access_www.log  /application/nginx/logs/access_www_`date +%F`.log
/application/nginx/sbin/nginx -s reload

包含判斷的腳本

[root@web01 logs]# cat /server/script/cut_nginx_log.sh
# ! /bin/sh
Dateformat=‘date +%Y%m%d‘
Basedir= "/application/nginx"
Nginxlogdir="$Basedir/logs"
Logname="access_www"
[-d $Nginxlogdir ] && cd $Nginxlogdir || exit 1
[-f ${Logname}.log ] || exit 1
/bin/mv ${Logname}.log ${Dateformat}_${Logname}.log
$Basedir/sbin/nginx -s reload

02.利用系統自帶切割軟件進行切割

cat /etc/logrotate.conf

4.9 企業需求解決(location應用)

1、搭建好一臺nginx的web服務器,配置好內網網卡地址與外網網卡地址

2、web服務器的網站域名為www.nmtui.com 站點目錄為 html/www

3、要求內網可以訪問 www.nmtui.com/AV 資源

4、要求外網不可以訪問 www.nmtui.com/AV 資源

4.9.1 需求處理 --location的應用

1、定位需要控制的資源

location == if

修改配置文件

[root@web01 extra]# cat www.conf
    server {
        listen       80;
        server_name  www.nmtui.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        location /AV  {
            root  html/www;
            index index.html index.htm;
            allow 172.16.1.0/24;
            deny  all;
        }
    }

4.9.2 location 語法

location 指令的作用是根據用戶請求的URI來執行不同的應用。

locationn使用的語法為

location [=|~|~*|^~] uri {
  ....
}

location 語法說明表

location

[=|~|~*|^~]

uri

{....}

指令

匹配標識

匹配的網站地址

匹配URI後要執行的配置段

~ 與~* 的區別

u ~ 匹配內容區分大小寫

u ~* 匹配內容不區分的小寫

u !~ 取反

u ^~ 但多個匹配同時存在,優先匹配 ^~匹配的內容;不做正則表達式的檢查 (優先處理)

4.9.3 官方配置示例

location = / {
    [ configuration A ]
}
 
location / {
    [ configuration B ]
}
 
location /documents/ {
    [ configuration C ]
}
 
location ^~ /images/ {
    [ configuration D ]
}
 
location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

說明:

"/"請求將匹配配置A,

"/index.html"請求將匹配配置B,

"/documents/document.html"請求將匹配配置C,

"/images/1.gif"請求將匹配配置D,

"/documents/1.jpg"請求將匹配配置E.

不同uri及特殊字符組合匹配的順序說明

順序

不用URI及特殊字符組合匹配

匹配說明

1

location = / {}

精確匹配 /

2

location ^~ /image/{

匹配常規字符串,不做正則表達式匹配檢查

3

location ~* \.(gif|jpg|jpeg)$ {

正則匹配

4

location /documents/ {

匹配常規字符串,如果有正則,則優先匹配正則

5

location / {

所有location 都不能匹配後的默認匹配

4.9.4 【測試】測試location的訪問

4.9.4.1 修改配置文件

定義不同的location返回不同的數值

[root@web01 extra]# vim www.conf
server {
    listen       80;
    server_name  www.nmtui.com nmtui.com;
    root   html/www;
    location / {
       return 401;
    }
    location = / {
        return 402;
    }
    location /documents/ {
        return 403;
    }
    location ^~ /images/ {
        return 404;
    }
    location ~* \.(gif|jpg|jpeg)$ {
    return 500;
    }
    access_log logs/access_www.log main;
}

4.9.4.2 訪問測試

根據請求不同uri的返回值驗證 location的配置。

[root@nfs01 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s  www.nmtui.com/documents
401
[root@nfs01 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s  www.nmtui.com
402
[root@nfs01 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s  www.nmtui.com/documents/ss.jpg
500
[root@nfs01 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s  www.nmtui.com/documents
401
[root@nfs01 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s  www.nmtui.com/documents/
403
[root@nfs01 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s  www.nmtui.com/images/1.jpg
404

4.10 rewrite 模塊的使用--地址重寫

4.10.1 rewrite 重寫模塊

將地址信息進行重寫

rewrite 語法格式

rewrite regex replacement [flag]

rewrite應用標簽:server、location、if

4.10.2 rewrite模塊兩個功能

1. 實現網站地址信息跳轉

2. 實現偽靜態

4.10.3 方法一 使用if判斷

[root@web01 extra]# cat www.conf
    server {
        listen       80;
        server_name  www.nmtui.com nmtui.cn;
if ($host ~* "^nmtui.com$") {
rewrite ^/(.*) http://www.nmtui.com/$1 permanent;
}
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        access_log  logs/access_www.log  main;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

測試

[root@web01 www]# curl  nmtui.com -L
web01 www

4.10.4 方法二 再添加上一個區塊

server {   
        server_name nmtui.com;
        rewrite ^/(.*) http://www.nmtui.com/$1 permanent;
}  

4.10.5 nginx 的rwite重寫企業應用場景

可以調整用戶瀏覽的URL,使其看起來更規範,合乎開發及產品人員的需求。

為了讓搜索引擎收錄網站內容,並讓用戶體驗更好,企業會將動態URL地址偽裝成靜態地址提供服務。

網站換新域名後,讓舊域名的訪問跳轉到新的域名上,例如:讓京東的360buy換成了jd.com。

根據特殊變量、目錄、客戶端的信息進行URL跳轉等。

說明:開源軟件類似wordpress的,官方都會對偽靜態配置進行說明

4.11 nginx 的訪問認證

4.11.1 修改nginx的相關配置文件

vim extra/www.conf
location / {
        root   html/www;
        index  index.html index.htm;
        auth_basic           "clsn training";
        auth_basic_user_file   /application/nginx/conf/htpasswd;
 }

4.11.2 創建密碼文件

註: 這裏使用的htpasswd命令默認是沒有的,需要通過yum install httpd-tools -y 安裝

[root@web01 extra]# htpasswd -c /application/nginx/conf/htpasswd clsn
New password:
Re-type new password:
Adding password for user clsn

參數說明:

-c Create a new file.

創建一個新的密碼文

-b Use the password from the command line rather than prompting for it.

采用免交互的方式輸入用戶的密碼信息

htpasswd參數說明

參數

參數說明

-c

創建一個新文件。

-n

不更新文件; 顯示結果。

-m

強制MD5密碼加密。

-d

強制CRYPT加密密碼(默認)。

-p

不加密密碼(明文)。

-s

強制SHA加密密碼。

-b

使用命令行中的密碼,而不是提示。(免交互)

-D

刪除指定的用戶。

4.11.3 更改密碼文件權限

[root@web01 extra]#  chmod 400 /application/nginx/conf/htpasswd    
[root@web01 extra]#  chown -R www.www /application/nginx/conf/htpasswd
[root@web01 extra]# cat /application/nginx/conf/htpasswd
clsn:e3OfMiJThE0Qg

4.11.4 重啟服務: 配置修改後要重啟服務

[root@web01 extra]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful
[root@web01 extra]# /application/nginx/sbin/nginx -s reload

4.11.5 訪問測試

# 使用交互式輸入密碼
[root@web01 www]# curl www.nmtui.com -uclsn
Enter host password for user ‘clsn‘:123456
web01 www
# 使用免交互輸入密碼
[root@web01 www]# curl www.nmtui.com -uclsn:123456
web01 www

Nginx服務企業應用