Nginx服務編譯安裝、日志功能、狀態模塊及訪問認證模式實操


系統環境

  [root@web ~]# cat /etc/redhat-release 
  CentOS release 6.9 (Final)
  [root@web ~]# uname -a
  Linux db02 2.6.32-696.el6.x86_64 #1 SMP Tue Mar 21 19:29:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Nginx介紹

  Nginx是一個開源的,支持高性能、高並發的WWW服務器和代理服務軟件

  官方資料:http://www.nginx.org/

  nginx軟件常見的使用方式或架構為:LNMP(linux nginx mysql php)

Nginx的特點或優勢

  •     支持高並發:能支持幾萬並發連接(特別是靜態小文件業務環境)
  •     資源消耗少:在3萬並發連接下,開啟10個Nginx線程消耗的內存不到200MB
  •     可以做HTTP反向代理及加速緩存、即負載均衡功能,內置對RS節點服務器健康檢查功能,這相當於專業的Haproxy軟件或LVS的功能。
  •     具備Squid等專業緩存軟件等的緩存功能。   
  •     支持異步網絡I/O事件模型epoll(Linux 2.6+)(繪圖說明同步和異步)

      大並發寫操作;先寫內存,再將內存數據存儲到硬盤中---保證訪問效率

      大並發讀操作;先寫磁盤,再將磁盤數據存儲到內存中---保證數據安全

  總結:高並發-->資源消耗少-->功能多樣(web服務/負載均衡/支持緩存)-->通訊模型先進(epoll)

Nginx編譯安裝步驟

一、解決nginx依賴包

需要的依賴:

  pcre:兼容perl語言正則表達式,perl compatible regular expressions rewirte模塊 參數信息(perl方式定義正則表達式)

  openssl:https

  注意:所有安裝依賴軟件,后面都要加上-devel

[root@web ~]# yum install -y pcre-devel openssl-devel
下載nginx
[root@web tools]# wget http://nginx.org/download/nginx-1.10.2.tar.gz
[root@web tools]# ll
total 892
-rw-r--r-- 1 root root 910812 Oct 24 10:26 nginx-1.10.2.tar.gz
解決依賴,下載nginx

二、解壓nginx、創建管理用戶、配置nginx

[root@web tools]# tar xf nginx-1.10.2.tar.gz
[root@web tools]# ll
total 896
drwxr-xr-x 8 1001 1001   4096 Oct 18  2016 nginx-1.10.2
-rw-r--r-- 1 root root 910812 Oct 24 10:26 nginx-1.10.2.tar.gz
[root@web tools]# cd nginx-1.10.2
[root@web nginx-1.10.2]# useradd -s /sbin/nologin www -M
[root@web nginx-1.10.2]# id www
uid=2223(www) gid=2223(www) groups=2223(www)
[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功能模塊 
解壓nginx、創建用戶、配置nginx

三、編譯&&編譯安裝

make && make install

給軟件創建軟連接文件,方便以后管理使用

[root@web application]# ln -s /application/nginx-1.10.2/ /application/nginx
[root@web application]# ll
total 4
lrwxrwxrwx 1 root root   26 Oct 24 10:51 nginx -> /application/nginx-1.10.2/
drwxr-xr-x 6 root root 4096 Oct 24 10:50 nginx-1.10.2
創建軟連接

四、啟動nginx服務

[root@web application]# /application/nginx/sbin/nginx 
[root@web application]# ps -ef |grep nginx
root  15342      1  0 10:56 ?   00:00:00 nginx: master process /application/nginx/sbinnginx
www   15343  15342  0 10:56 ?  00:00:00 nginx: worker process  
        
root  15345  12539  0 10:56 pts/0    00:00:00 grep --color=auto nginx
啟動nginx

軟件安裝完目錄信息

  conf             --- 軟件配置文件保存目錄

  html             --- 網站站點目錄*

  logs             --- 日志文件保存目錄

  sbin             --- nginx命令保存目錄

conf目錄中內容

  nginx.conf             --- nginx程序的主配置文件

  nginx.conf.default    --- nginx配置備份文件

因為初始化的nginx配置文件內有較多注釋,影響對配置文件的修改,所以進行精簡化配置文件

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

nginx軟件啟動重啟方法

啟動方法(全路徑) 
/applocation/nginx/sbin/nginx 
停止方法(全路徑+   -s 參數 接指令)
/applocation/nginx/sbin/nginx -s stop
平滑重啟方法(全路徑+   -s 參數 接指令)
/applocation/nginx/sbin/nginx -s reload
檢查配置文件語法(全路徑+  -t 參數)
/applocation/nginx/sbin/nginx -t
查看怎么部署的(全路徑+   -V 參數)
/applocation/nginx/sbin/nginx -V
nginx重啟方式

Nginx配置文件配置詳解

在server模塊下指定主頁文件,可以指定自己寫的主頁,這里需要注意的是,主頁文件要放到站點目錄下

[root@web nginx]# cat conf/nginx.conf
worker_processes  1;                        ##worker進程數量
events {
    worker_connections  1024;               ##每個worker進程支持的最大連接數
}
http {
    include       mime.types;               ##Nginx支持的媒體類型庫文件
    default_type  application/octet-stream; ##默認的媒體類型
    sendfile        on;                     ##開啟高效傳輸模式
    keepalive_timeout  65;                  ##連接超時
    server {
        listen       80;                    ##提供服務的端口,默認是80
        server_name  www.zxpo.top;          ##提供服務的域名主機名
        location / {
            root   html/www;                ##站點的根目錄,相當於Nginx的安裝目錄
            index  index.html index.htm;   ##默認的首頁文件,多個用空格分開
        }
        error_page   500 502 503 504  /50x.html;    ##出現對應的狀態碼,使50x.html
        location = /50x.html {
            root   html;                    ##指定對應的站點目錄為html
        }
    }
}
配置文件詳解

多個server模塊堆在一個配置文件中比較亂,難以修改,可以將配置文件分為多個,一個nginx.conf為主,例如

創建一個exyra目錄為存放不同站點的配置文件目錄,將不同網頁的server模塊寫成不同的配置文件,然后引用

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    include     extra/www.conf;
    include     extra/blog.conf;
    include     extra/bbs.conf;
}

Nginx使用

基於域名訪問

  在server模塊中設置,server模塊可以有多個,server_name,可以修改成不同的域名,如果是本地測試的話,記得host文件解析

 server {
        listen       80;
        server_name  www.zxpo.top;          <- 修改虛擬主機域名名稱
        location / {
            root   html/www;                <- 修改虛擬主機站點目錄
            index  index.html index.htm;
        }

基於端口訪問

server {
        listen       81;      <- 將端口換成81,進行測試
        server_name  bbs.zxpo.top;
        location / {
            root   html/bbs;
            index  index.html index.htm;
        }

檢查

[root@web nginx]# netstat -lntup|grep nginx
tcp        0      0 0.0.0.0:80       0.0.0.0:*         LISTEN      15342/nginx         
tcp        0      0 0.0.0.0:81       0.0.0.0:*         LISTEN      15342/nginx

基於IP訪問

  注意:采用基於IP配置虛擬主機,修改完配置文件后,需要重啟配置文件,不能夠采用平滑重啟。

        只要配置文件中,有關IP地址相關的改動,都需要進行重啟nginx服務,不能夠采用平滑重啟。

改配置文件

server {
        listen       10.0.0.8:80;   <-改成某個ip還有指定的端口
        server_name  www.zxpo.top;
        location / {
            root   html/www;
            index  index.html index.htm;
        }

然后重啟

curl訪問網站流程

[root@web ~]# curl -v www.zxpo.top         <- 利用curl命令-v參數獲取訪問網站流程
a. 訪問網站時首先需要根據域名解析獲取到網站的ip地址,找尋網站的ip地址對應的服務器
b. 訪問網站時其次需要根據請求建立連接的目標端口信息,找尋網站的相應服務端口是否存在
c. 訪問網站時再次需要根據請求域名信息獲悉相應的站點,找尋網站的相應站點目錄下的資源信息
d. 訪問網站時最后如果ip地址加端口信息都已找到,但沒有找到對應的域名信息,會按照默認原則使用第一個虛擬主機作為默認訪問的虛擬站點目錄

Nginx共享文件web頁面

  當配置autoindex on參數以后,會顯示站點目錄文件列表信息:

   1. 對於nginx服務可以識別解析資源,進行點擊,會顯示相應內容

   2. 對於nginx服務不可以識別解析資源,進行點擊,會直接下載

server {
        listen       80;
        server_name  www.zxpo.com;
        location / {
            root   html/www;           <-或者在設置一級專門做共享的目錄
          index  index.html index.htm; <-這里要在站點目錄中把主頁文件刪除,否則會直接顯示主頁
            autoindex on;
        }

查看Nginx狀態信息配置

  stub_status模塊主要用於查看Nginx的一些狀態信息

       在主配置文件配置  log_format main……

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"';
省略……

訪問狀態信息:

  Active connections   客戶端連接數

  accepts   接收數值

  handled   處理數值(通常跟接收值是一樣的,但是限制值達到上限就例外了)

  requests  客戶端請求值

  Reading   請求報文的連接數

  Writing   響應

  Waiting   等待請求的數量

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

 Nginx日志功能

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.html

錯誤日志信息

  記錄nginx服務運行異常情況信息

error_log的默認值為:
error_log logs/error.log error;
可以放置的標簽段為(可以設置的區塊):
main,http,server,location

  參考資料:http://nginx.org/en/docs/ngx_core_module.html#error_log

  說明:nginx官方文檔查詢信息如何使用,如何根據配置信息獲取所在模塊目錄

配置文件中設置錯誤日志

error_log  logs/error.log  error;  

訪問日志信息

Nginx日志格式中默認的參數配置如下:
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';
Nginx記錄日志的默認參數配置如下:
access_log  logs/access.log  main;

配置文件中設置訪問日志

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"';

access_log  logs/access.log  main;
……

日志信息說明

這是一條日志文件中的日志信息:

10.0.0.253 - - [25/Oct/2017:15:32:35 +0800] "GET /favicon.ico HTTP/1.1" 404 571 "http://www.zxpo.top/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"
$remote_addr    10.0.0.253       客戶端IP地址信息
$remote_user    -                遠程認證用戶信息
[$time_local]     [24/Oct/2017:23:19:29 +0800]       顯示訪問事件信息
$request        GET / HTTP/1.1   表示顯示請求行內容
$status        200               顯示狀態碼信息(若日志中,狀態碼為304,表示用戶端有緩存信息)
$body_bytes_sent   10            響應保存主體內容大小
$http_user_agent                 定義客戶端以什么軟件進行訪問web服務器

Nginx日志切割方式

利用腳本切割

#!/bin/bash
/application/nginx/sbin/nginx -s reload    #先重啟一次生成日志

mv /application/nginx/logs/access_www.log /application/nginx/logs/access_www_$(date +%F).log    #然后改名

/application/nginx/sbin/nginx -s reload    #再次重啟重新生成新的

具體切割日志腳本

[root@www 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

logrotate方式切割

 logrotate配置文件詳解

 

/var/log/nginx/*.log { #/var/log/nginx/日志的存儲目錄,可以根據實際情況進行修改
daily                ##日志文件將按天輪循
weekly               ##日志文件將按周輪循
monthly              ##日志文件將按月輪循
missingok            ##在日志輪循期間,任何錯誤將被忽略,例如“文件無法找到”之類的錯誤
rotate 7             #一次存儲7個日志文件。對於第8個日志文件,時間最久的那個日志文件將被刪除
dateext              #定義日志文件后綴是日期格式,也就是切割后文件是:xxx.log-20160402.gz這樣的格式。如果該參數被注釋掉,切割出來是按數字遞增,即前面說的 xxx.log-1這種格式
# compress           ##在輪循任務完成后,已輪循的歸檔將使用gzip進行壓縮
delaycompress        ##總是與compress選項一起用,delaycompress選項指示logrotate不要將最近的歸檔壓縮,壓縮將在下一次輪循周期進行。這在你或任何軟件仍然需要讀取最新歸檔時很有用
notifempty           ##如果是空文件的話,不進行轉儲
create 640 nginx adm ##以指定的權限和用書屬性,創建全新的日志文件,同logrotate也會重命名原始日志文件
sharedscripts        ##表示postrotate腳本在壓縮了日志之后只執行一次
postrotate        
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid` endscript }
## postrotate/endscript:在所有其它指令完成后,postrotate和endscript里面指定的命令將被執行。在這種情況下,rsyslogd進程將立即再次讀取其配置並繼續運行。注意:這兩個關鍵字必須單獨成行

Nginx的location作用

 進行策略控制

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

  location表示位置的概念,類似於if,即滿足什么條件,就做什么

  控制訪問網段,設置訪問網段白名單和黑名單

[root@web01 www]# cat /application/nginx/conf/extra/www.conf 
    server {
        listen       80;
        server_name  www.etiantian.org t.org;
        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;             ##其余網段拒絕
        }
   }

location匹配說明

 

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

匹配說明

location = / {

精確匹配 /

location ^~ /images {

匹配常規字符串,不做正則匹配檢查(優先)

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

正常匹配,匹配后綴為gif|jpg|jpeg的

location /documents/ {

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

location / {

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

~   : 匹配內容區分大小寫

~*  :匹配內容不區分大小寫

  :表示取反匹配

^~  :表示當多個匹配同時存在,優先匹配^~內容

Nginx 的訪問認證

修改nginx的相關配置文件

    server {
        listen      80;
        server_name  www.zxpo.top;
        location / {
            root   html/www;
            index  index.html index.htm;
            auth_basic       "erlianzhang training";
            auth_basic_user_file    /application/nginx/conf/htpasswd;
       }

創建密碼認證文件並進行授權

 首先要下載httpd-tools軟件

yum install httpd-tools -y

htpasswd的參數

[root@web application]# htpasswd -hlep
Usage:
    htpasswd [-cmdpsD] passwordfile username
    htpasswd -b[cmdpsD] passwordfile username password
    htpasswd -n[mdps] username
    htpasswd -nb[mdps] username password
 -c      Create a new file.
        創建一個新的密碼文件
 -n      Don't update file; display results on stdout.
        不更新文件,顯示輸出結果
 -m      Force MD5 encryption of the password.
        強制采用MD5加密密碼
 -d      Force CRYPT encryption of the password (default).
        強制采用CRYPT加密密碼(默認)
 -p      Do not encrypt the password (plaintext).
        不加密密碼(明文) 
 -s      Force SHA encryption of the password.
        強制采用SHA加密密碼
 -b      Use the password from the command line rather than prompting for it.
        使用密碼來自命令行,相當於免交互方式
 -D      Delete the specified user.
        刪除指定用戶
On Windows, NetWare and TPF systems the '-m' flag is used by default.
On all other systems, the '-p' flag will probably not work.
htpasswd參數詳解

創建認證文件

[root@web www]# htpasswd -bc /application/nginx/conf/htpasswd lyq 123456
Adding password for user oldboy
[root@web01 www]# cat /application/nginx/conf/htpasswd 
lyq:DVu6f44f2I81w    <- 加密的認證文件自動設置密文
認證文件生成

給密碼文件授權,重啟Nginx

[root@web www]# chown -R www.www /application/nginx/conf/htpasswd
[root@web www]# chmod 400 /application/nginx/conf/htpasswd
[root@web www]# /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@web www]# /application/nginx/sbin/nginx -s reload
授權密碼文件,重啟nginx

登陸測試

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM