7.Web基礎之Nginx

1. Nginx基本概述

nginx是一個開源且高性能、可靠的http web服務、代理服務。
開源:直接獲取源代碼
高性能:支持海量併發
可靠:服務穩定html

1.1 咱們爲何選擇Nginx服務

1.1.1 nginx很是輕量

功能模塊少(源代碼僅保留http與核心模塊代碼,其他不夠核心代碼會做爲插件來安裝)
代碼模塊化(易讀,便於二次開發,對於開發人員很是友好)html5

1.1.2 互聯網公司都選擇nginx

1.nginx技術成熟,具有的功能是企業最常使用並且最須要的
2.適合當前主流架構趨勢,微服務,雲架構,中間層
3.統一技術棧,下降維護成本,下降技術更新成本。nginx

1.1.3 nginx採用Epool網絡模型,Apache採用select模型

select:當用戶發起一次請求,select模型就會進行一次遍歷掃描,從而致使性能低下;
Epool:當用戶發起請求,epool模型會直接進行處理,效率高效,並沒有鏈接限制。c++

Nginx典型應用場景-cweb

2. Nginx快速安裝

nginx軟件安裝方式有不少種apache

1.源碼編譯==>Nginx(1.版本隨意 2.安裝複雜 3.升級繁瑣)
2.epel倉庫==>Nginx(1.版本較低 2.安裝簡單 3.配置不易讀)
3.官方倉庫==>Nginx(1.版本較新 2.安裝簡單 3.配置易讀,推薦)json

2.1 安裝Nginx軟件所需依賴包

[root@web01 ~]# yum install -y gcc gcc-c++ pcre pcre-devel openssl openssl-devel

2.2 配置Nginx官方yum源

[root@web01 ~]# vim /etc/yum.repos.d/nginx.repo 

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

2.3 安裝Nginx服務,啓動並假如開機自啓

[root@web01 ~]# yum install -y nginx
[root@web01 ~]# systemctl start nginx
[root@web01 ~]# systemctl enable nginx

2.4 經過瀏覽器訪問該服務器ip活url地址

-c

2.5 檢查Nginx軟件版本以及編譯參數

[root@web01 ~]# nginx -v
nginx version: nginx/1.16.0
[root@web01 ~]# nginx -V
nginx version: nginx/1.16.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
[root@web01 ~]#

2.6 Nginx配置

爲了讓你們更清晰的瞭解Nginx軟件的全貌,可以使用rpm -ql nginx 查看真題的目錄結構及對應的功能,以下表格整理了Nginx比較重要的配置文件vim

2.6.1 Nginx主配置文件

路徑 類型 做用
/etc/nginx/nginx.conf 配置文件 nginx主配置文件
/etc/nginx/conf.d/default.conf 配置文件 默認網站配置文件

2.6.2 Nginx代理相關參數文件

路徑 類型 做用
/etc/nginx/fastcgi_params 配置文件 fastcgi代理配置文件
/etc/nginx/scgi_params 配置文件 scgi代理配置文件

2.6.3 Nginx編碼相關參數文件

路徑 類型 做用
/etc/nginx/win-utf 配置文件 Nginx編碼轉換映射文件
/etc/nginx/koi-utf 配置文件 Nginx編碼轉換映射文件
/etc/nginx/koi-win 配置文件 Nginx編碼轉換映射文件
/etc/nginx/mime.types 配置文件 Content-Type與擴展名

2.6.4 Nginx管理相關命令

路徑 類型 做用
/usr/sbin/nginx 命令 Nginx命令行管理終端工具
/usr/sbin/nginx-debug 命令 Nginx命令行與終端調試工具

2.6.5 Nginx日誌相關目錄與文件

路徑 類型 做用
/var/log/nginx 目錄 Nginx默認存放日誌目錄
/etc/logrotate.d/nginx 配置文件 Nginx默認的日誌切割

3. Nginx默認配置

Nginx主配置文件/etc/nginx/nginx.conf是一個純文本類型的文件,整個配置文件是以區塊的形式組織的。通常每一個區塊以一對大括號{}來表示開始與結束。
Nginx主配置文件總體分爲三塊進行學習,分別是CoreModule(核心模塊)、EventModule(事件驅動模塊)、HttpCoreModule(http內核模塊)windows

CoreModule(核心模塊)centos

user  nginx;                                #Nginx進程所使用的用戶
worker_processes  1;                        #Nginx運行的work進程數量(建議與CPU數量一致或auto)
error_log  /var/log/nginx/error.log warn;   #Nginx錯誤日誌存放路徑(警告及警告以上的都會記錄)
pid        /var/run/nginx.pid;              #Nginx服務運行後產生的pid進程號

EventModule(事件驅動模塊)

events {
worker_connections  1024;                   #每一個worker進程支持的最大鏈接數
use epool                                   #事件驅動模型,epoll默認
}

HttpCoreModule(http內核模塊)

http {
    include       /etc/nginx/mime.types;            #包含資源類型文件
    default_type  application/octet-stream;         #默認如下載方式傳輸給瀏覽器(前提是該資源在mime.types中沒法找到)
    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  /var/log/nginx/access.log  main;    #訪問日誌
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;                          #長鏈接超時時間
    #gzip  on;                                      #是否開啓壓縮功能
    include /etc/nginx/conf.d/*.conf;               #包含的配置文件

server {
    listen       80;                                #監聽端口
    server_name  localhost;                         #域名
    #charset koi8-r;                                #字符集
    #access_log  /var/log/nginx/host.access.log  main;   #訪問日誌
    location / {                                    #存放網站路徑
        root   /usr/share/nginx/html;               #默認訪問首頁文件
        index  index.html index.htm;
    }
}

**http server location擴展瞭解項

① http{}層下容許有許多個server{}層,一個server{}層下又容許有多個location
② http{}標籤主要用來解決用戶的請求與響應
③ server{}標籤主要用來響應具體的某一個網站
④ location{}標籤主要用於匹配網站具體URL路徑**

4. Nginx搭建web網站

4.1 配置nginx配置文件

[root@web01 ~]# cat /etc/nginx/conf.d/game.conf 
server {
        listen 80;
        server_name game.oldboy.com;

        location / {
                root /data;
                index index.html;
        }   
}

4.2 放置遊戲源代碼文件至nginx配置文件root指定的目錄

[root@web01 ~]# mkdir /data && cd /data
[root@web01 data]# rz html5.zip
[root@web01 data]# unzip html5.zip
[root@web01 data]# ll
total 18848
drwxr-xr-x 23 root root     4096 Mar  5  2015 ceshi
drwxr-xr-x 42 root root     4096 Mar  5  2015 game
-rw-r--r--  1 root root 19248295 Jan 17  2019 html5.zip
drwxr-xr-x  2 root root     4096 Mar  5  2015 img
-rwxr-xr-x  1 root root    30312 Mar  5  2015 index.html
drwxrwxr-x  5 root root      124 Dec  9  2018 __MACOSX
-rwxr-xr-x  1 root root      578 Mar  5  2015 readme.txt
[root@web01 data]#

4.3 檢查nginx語法是否存在錯誤

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

4.4 從新加載nginx [ reload | restart ]

[root@web01 data]# systemctl restart nginx

4.5 配置hosts訪問域名

10.0.0.7  game.oldboy.com

5. Nginx虛擬主機

一般在企業中可能會有不少業務系統,那麼多套業務服務如何使用nginx配置?

-c

若是使用如上方式部署,則須要多臺服務器配置nginx,但若是使用虛擬主機方式,則在同一個nginx上運行多套單獨服務,這些服務是相互獨立的,簡單來講,看似多套業務系統,實則能夠運行在一臺nginx服務上

-c

5.1 Nginx虛擬主機Nginx配置虛擬主機有三種方式:

方式一:基於主機多IP方式方式二:基於端口的配置方式方式三:基於多個hosts名稱方式(多域名方式)

5.2 基於多IP的虛擬主機配置實戰

-c

基於多IP的方式,有以下兩種方式:

-c

5.2.1 配置多網卡多IP的方式

樣板:
server {
    ...
    listen 10.0.0.10:80;
    ...
}

server {
    ...
    listen 10.0.0.11:80;
    ...
}
實例:
#1.修改nginx配置
[root@web01 ~]# cat /etc/nginx/conf.d/ip.conf 
server {
        listen 10.0.0.7:80;
        server_name _;

        location / {
                root /code_ip_eth0;
                index index.html;
        }
}

server {
        listen 172.16.1.7:80;
        server_name _;

        location / {
                root /code_ip_eth1;
                index index.html;
        }
}

#2.建立配置指定目錄
[root@web01 ~]# echo "Eth0" > /code_ip_eth0/index.html
[root@web01 ~]# echo "Eth1" > /code_ip_eth1/index.html

#3.重啓nginx服務
[root@web01 ~]# systemctl restart nginx

#4.使用curl命令測試訪問
[root@web01 ~]# curl 10.0.0.7
Eth0
[root@web01 ~]# curl 172.16.1.7
Eth1
[root@web01 ~]#

5.2.2 配置單網卡多IP的方式(不必)

#添加一個IP
[root@web01 ~]# ip addr add 10.0.0.11/24 dev eth0

#虛擬機配置方案
[root@web01 ~]# cat /etc/nginx/conf/conf.d/addr1.conf
server {
        ...
        listen 10.0.0.7:80;
        ...
}

[root@web01 ~]# cat /etc/nginx/conf/conf.d/addr2.conf
server {
        ...
        listen 10.0.0.11:80;
        ...
}

5.3 基於端口的虛擬主機配置實戰

樣板:
server {
    ...
    listen 81;
    ...
}

server {
    ...
    listen 82;
    ...
}
實例:
#1.修改nginx配置
[root@web01 ~]# cat /etc/nginx/conf.d/port.conf 
server {
        listen 81;

        location / {
                root /code_81;
                index index.html;
        }
} 

server {
        listen 82;

        location / {
                root /code_82;
                index index.html;
        }   
} 

#2.建立指定目錄並寫入文件
[root@web01 ~]# mkdir /code_8{1..2}
[root@web01 ~]# echo "81" > /code_81/index.html
[root@web01 ~]# echo "82" > /code_82/index.html

#3.重啓nginx服務
[root@web01 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 ~]# systemctl restart nginx

#瀏覽器訪問測試
10.0.0.7:81
10.0.0.7:82

5.4 基於多個hosts的虛擬主機配置實戰

樣板:
server {
    ...
    listen 80;
    server_name test1.oldboy.com;
    ...
}

server {
    ...
    listen 80;
    server_name test2.oldboy.com;
    ...
}
實例:
#1.添加多主機nginx配置文件
[root@web01 ~]# cat /etc/nginx/conf.d/test1.oldboy.com.conf 
server {
        listen 80;
        server_name test1.oldboy.com;

        location / {
                root /code/test1;
                index index.html;
        } 
}
[root@web01 ~]# cat /etc/nginx/conf.d/test2.oldboy.com.conf 
server {
        listen 80;
        server_name test2.oldboy.com;

        location / {
                root /code/test2;
                index index.html;
        }
}
[root@web01 ~]#

#2.建立指定目錄並寫入文件
[root@web01 ~]# mkdir /code/test{1..2}
[root@web01 ~]# echo "test1_server" > /code/test1/index.html
[root@web01 ~]# echo "test2_server" > /code/test2/index.html

#3.重啓nginx服務
[root@web01 ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 ~]# systemctl restart nginx

#配置域名解析 windows下 C:\Windows\System32\drivers\etc\hosts
10.0.0.7  test1.oldboy.com
10.0.0.7  test2.oldboy.com

#瀏覽器訪問測試
test1.oldboy.com
test2.oldboy.com

6. Nginx日誌管理

Nginx有很是流火的日誌記錄模式,每一個級別的配置能夠有個字獨立的訪問日誌。日誌格式經過log_format命令定義格式。

6.1 nginx自查

1.修改完配置記得使用 nginx -t 檢查語法
2.若是沒有檢查語法,直接重載致使報錯。systemctl status nginx -l 查看錯誤信息

6.2 配置語法: 包括: error.log access.log

log_format命令定義日誌格式語法

Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http

6.3 Nginx默認定義語法

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

6.4 Nginx日誌格式容許包含的內置變量

$remote_addr            #表示客戶端地址
$remote_user            #http客戶端請求nginx認證用戶名
$time_local             #Nginx的時間
$request                #Request請求行, GET等方法、http協議版本
$status                 #respoence返回狀態碼
$body_bytes_sent        #從服務端響應給客戶端body信息大小
$http_referer           #http上一級頁面, 防盜鏈、用戶行爲分析
$http_user_agent        #http頭部信息, 客戶端訪問設備
$http_x_forwarded_for   #http請求攜帶的http信息

$time_iso8601           #記錄ISO8601標準格式下的本地時間
$bytes_sent             #發送給客戶端的總字節數
$msec                   #日誌寫入時間,單位爲秒,精度是毫秒
$request_length         #請求的長度(包括請求行,請求頭和請求正文)
$request_time           #請求話費的時間,單位爲秒,精度毫秒
# 注:若是Nginx位於負載均衡器,nginx反向代理以後,web服務器沒法直接獲取到客戶端真是的IP地址。
# $remote_addr 獲取的是反向代理的IP地址;反向代理服務器在轉發請求的http頭信息中。
# 增長X-Forwarded-For信息,用來記錄客戶端IP地址和客戶端請求的服務器地址。

6.5 access_log日誌配置語法

官網語法格式

Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default: access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except

6.6 nginx access_log日誌配置實踐

server {
        listen 80;
        server_name code.oldboy.com;

        #將當前的server網站的訪問日誌記錄至對應的目錄,使用main格式
        access_log /var/log/nginx/code.oldboy.com.log main;
        location / {
                root /code;
        }

        #當有人請求改favicon.ico時,不記錄日誌
        location /favicon.ico {
                access_log off;
                return 200;
        }
}

6.7 nginx 日誌切割logrotate

[root@web01 ~]# cat /etc/logrotate.d/nginx 
/var/log/nginx/*.log {
        daily                       #天天切割日誌
        missingok                   #日誌丟失忽略
        rotate 52                   #日誌保留52天
        compress                    #日誌文件壓縮
        delaycompress               #延遲壓縮日誌
        notifempty                  #不切割空文件
        create 640 nginx adm        #日誌文件權限
        sharedscripts
        postrotate                  #切割日誌執行的命令
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}
[root@web01 ~]#

6.8 nginx 日誌切割後效果

[root@web01 ~]# cd /var/log/nginx/
[root@web01 nginx]# ll
total 20
-rw-r----- 1 nginx adm  3162 Jul 31 21:27 access.log
-rw-r----- 1 nginx adm   410 Jul 30 17:41 access.log-20190731
-rw-r----- 1 nginx adm  2036 Jul 31 21:33 error.log
-rw-r----- 1 nginx adm   246 Jul 30 17:41 error.log-20190731
-rw-r--r-- 1 root  root 2667 Jul 31 21:33 test1.log
相關文章
相關標籤/搜索