linux高階-Nginx服務(五)-核心配置詳解

Nginx核心配置詳解

全局配置

user  nginx nginx;                 # 啓動Nginx⼯作進程的⽤⼾和組
worker_processes  [number | auto]; # 啓動Nginx⼯作進程的數量
worker_cpu_affinity 00000001 00000010 00000100 00001000;
# 將Nginx⼯作進程綁定到指定的CPU核⼼,默認Nginx是不進⾏進程綁定的,綁定並不是意味着當前nginx進程獨
# 佔以⼀核⼼CPU,但是可以保證此進程不會運⾏在其他核⼼上,這就極⼤減少了nginx的⼯作進程在不同的cpu核
# ⼼上的來回跳轉,減少了CPU對進程的資源分配與回收以及內存管理等,因此可以有效的提升nginx服務器的性
# 能。 此處CPU有四顆核心。也可寫成:
worker_cpu_affinity 0001 0010 0100 1000;


# 錯誤⽇志記錄配置,語法:error_log file  [debug | info | notice | warn | error | crit | alert | emerg]
# error_log  logs/error.log;
# error_log  logs/error.log  notice;
error_log  /apps/nginx/logs/error.log error;

# pid⽂件保存路徑
pid        /apps/nginx/logs/nginx.pid;

worker_priority 0; # ⼯作進程nice值,-20~19
worker_rlimit_nofile 65536; # 這個數字包括Nginx的所有連接(例如與代理服務器的連接等),⽽不僅僅是與
                            # 客⼾端的連接,另⼀個考慮因素是實際的併發連接數不能超過系統級別的最⼤打開⽂件數的限制.
[root@s2 ~]# watch -n1  'ps -axo pid,cmd,nice | grep nginx' #驗證進程優先級

daemon off;  # 前臺運⾏Nginx服務⽤於測試、docker等環境。
master_process off|on; #是否開啓Nginx的master-woker⼯作模式,僅⽤於開發調試場景。

events { # 事件模型配置參數
    worker_connections  65536;  # 設置單個⼯作進程的最⼤併發連接數
    use epoll; # 使⽤epoll事件驅動,Nginx⽀持衆多的事件驅動,⽐如select、poll、epoll,只能設置在events模塊中設置。
    accept_mutex on; # 優化同⼀時刻只有⼀個請求⽽避免多個睡眠進程被喚醒的設置,on爲防⽌被同時喚醒默
                     # 認爲off,全部喚醒的過程也成爲"驚羣",因此nginx剛安裝完以後要進⾏適當的優化。
    multi_accept on; # Nginx服務器的每個⼯作進程可以同時接受多個新的⽹絡連接,但是需要在配置⽂件中
                     # 配置,此指令默認爲關閉,即默認爲⼀個⼯作進程只能⼀次接受⼀個新的⽹絡連接,打開後⼏個同時接受多個。
}

http詳細配置

http {
    include       mime.types; # 導⼊⽀持的⽂件類型
    default_type  application/octet-stream; # 設置默認的類型,會提⽰下載不匹配的類型⽂件

    # ⽇志配置部分
    # 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;

    # ⾃定義優化參數
    sendfile        on; # 實現⽂件零拷⻉
    #tcp_nopush     on; # 在開啓了sendfile的情況下,合併請求後統⼀發送給客⼾端。
    #tcp_nodelay    off; # 在開啓了keepalived模式下的連接是否啓⽤TCP_NODELAY選項,當爲off時,延
                         # 遲0.2s發送,默認On時,不延遲發送,⽴即發送⽤⼾相應報⽂。
    #keepalive_timeout  0;
    keepalive_timeout  65 65; # 設置會話保持時間
    #gzip  on; # 開啓⽂件壓縮

server {
        listen       80; # 設置監聽地址和端⼝
        server_name  localhost; # 設置server name,可以以空格隔開寫多個並⽀持正則表達式,如
                                # *.magedu.com www.magedu.* www.(site\d+)\.magedu\.com$ default_server
        #charset koi8-r; # 設置編碼格式,默認是俄語格式,可以改爲utf-8
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html; # 定義錯誤⻚⾯
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ { #以http的⽅式轉發php請求到指定web服務器
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ { #以fastcgi的⽅式轉發php請求到php處理
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht { #拒絕web形式訪問指定⽂件,如很多的⽹站都是通過.htaccess⽂件來改變⾃⼰的重定向等功能。
        #    deny  all;
        #}
        location ~ /passwd.html {
            deny  all;
        }
        }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server { #⾃定義虛擬server
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm; #指定默認⽹⻚⽂件,此指令由ngx_http_index_module模塊提供

    #    }
    #}

    # HTTPS server
    #
    #server { #https服務器配置
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    location  /linux38/passwd.ht {
      deny  all;
     }

    #}

核心配置示例

  • 基於不同的IP、不同的端⼝以及不⽤得域名實現不同的虛擬主機,依賴於核⼼模塊ngx_http_core_module實現。
//修改主配置文件設置,子配置文件路徑
vim /apps/nginx/conf/nginx.conf

//http塊中添加,子配置文件路徑
include /apps/nginx/conf/conf.d/*.conf;
--------------------------
//新建編輯pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf

//配置文件內容
server{
listen 80;
server_name www.pc.com;
location / {
	root /data/nginx/html/pc;
}
}
---------------------------
//新建編輯mobile端子配置文件
vim /apps/nginx/conf/conf.d/mobile.conf

//配置文件內容
server{
listen 80;
server_name www.mobile.com;
location / {
    root /data/nginx/html/mobile;                                              
}
}
-----------------------------
//創建測試頁面
echo "this is pc web" > /data/nginx/html/pc/index.html

echo "this is mobile web" > /data/nginx/html/mobile/index.html

//重新加載配置文件
/apps/nginx/sbin/nginx -s reload 

//修改windows中hosts文件內容添加
172.20.26.104   www.pc.com
172.20.26.104   www.mobile.com
  • 瀏覽器訪問http://www.pc.com/得

在這裏插入圖片描述

  • 瀏覽器訪問http://www.mobile.com/得

在這裏插入圖片描述

  • root與alias
  • root:指定web的家⽬錄,在定義location的時候,⽂件的絕對路徑等於 root+location,如:
//編輯pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf

//配置文件如下
server{
listen 80;
server_name www.pc.com;
location / {
	root /data/nginx/html/pc;
}
location /images{
	root /data/nginx/html/pc   #必須要在/pc目錄中創建/images目錄存放圖片纔可訪問
	index index.html
}
}
----------------------------------------
//查看圖片存放位置
tree /data/nginx/html/pc/images/

/data/nginx/html/pc/images/
└── ms.jpg

  • 瀏覽器訪問http://www.pc.com/images/ms.jpg得

在這裏插入圖片描述

  • alias:定義路徑別名,會把訪問的路徑重新定義到其指定的路徑,如:
//編輯pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf

server{
listen 80;
server_name www.pc.com;
location / {
	root /data/nginx/html/pc;
}
location /images{ #使⽤alias的時候uri後⾯如果加了斜槓則下⾯的路徑配置必須加斜槓,否則403
	alias /data/nginx/html/pc   #當訪問images的時候,會顯⽰alias定義的/data/nginx/html/pc⾥⾯的
內容。
	index index.html
}
}
-------------------------------------------
//查看圖片存放位置
tree /data/nginx/html/pc/

/data/nginx/html/pc/
├── images
├── index.html
└── ms.jpg
  • 瀏覽器訪問http://www.pc.com/images/ms.jpg得

在這裏插入圖片描述

Nginx四層訪問控制

location /about {
alias /data/nginx/html/pc;
index index.html;
deny 192.168.1.1;   #拒絕地址
allow 192.168.1.0/24;   #允許網段
allow 10.1.1.0/16;   #允許網段
allow 2001:0db8::/32;   #允許IPV6地址
deny all; #先允許⼩部分,再拒絕⼤部分
}

Nginx賬戶認證功能

//安裝httpd工具包
yum -y install httpd-tools   #centos

apt -y isntall apache2-utils   #ubuntu

//設置用戶1以及密碼
htpasswd -cbm /apps/nginx/conf/.htpasswd bokebi1 123456
Adding password for user bokebi1

//設置用戶2以及密碼
htpasswd -bm /apps/nginx/conf/.htpasswd bokebi2 123456
Adding password for user bokebi2

//查看密碼文件
tail /apps/nginx/conf/.htpasswd
user1:$apr1$Rjm0u2Kr$VHvkAIc5OYg.3ZoaGwaGq/
user2:$apr1$nIqnxoJB$LR9W1DTJT.viDJhXa6wHv.

//編輯pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf
location = /login/ {
root /data/nginx/html/pc;
index index.html;
auth_basic "login password";   #加入這行
auth_basic_user_file /apps/nginx/conf/.htpasswd;   #指定用戶密碼存放路徑
}
重啓nginx並訪問測試

自定義錯誤頁面

listen 80;
server_name www.magedu.net;
error_page 500 502 503 504 404 /error.html;
location = /error.html {
root html;
}
重啓nginx並訪問不存在的⻚⾯進⾏測試

自定義訪問日誌

[root@s2 ~]# mkdir /data/nginx/logs
listen 80;
server_name www.magedu.net;
error_page 500 502 503 504 404 /error.html; #默認⽬錄下⾯創建error.html⻚⾯
access_log /data/nginx/logs/www-magedu-net_access.log;   #nginx用戶要對創建的目錄有操作權限
error_log /data/nginx/logs/www-magedu-net_error.log;   #nginx用戶要對創建的目錄有操作權限
location = /error.html {
root html;
}
重啓nginx並訪問不存在的⻚⾯進⾏測試並驗證是在指定⽬錄⽣成新的⽇志⽂件

檢測文件是否存在

  • try_files會按順序檢查⽂件是否存在,返回第⼀個找到的⽂件或⽂件夾(結尾加斜線表⽰爲⽂件夾),如果所有⽂件或⽂件夾都找不到,會進⾏⼀個內部重定向到最後⼀個參數。只有最後⼀個參數可以引起⼀個內部重定向,之前的參數只設置內部URI的指向。最後⼀個參數是回退URI且必須存在,否則會出現內部500錯誤。
location /about {
root /data/nginx/html/pc;
#alias /data/nginx/html/pc;
index index.html;
#try_files $uri /about/default.html;
#try_files $uri $uri/index.html $uri.html /about/default.html;
try_files $uri $uri/index.html $uri.html =489;
}
[root@s2 ~]# echo "default" >> /data/nginx/html/pc/about/default.html
重啓nginx並測試,當訪問到http://www.pc.com/about/xx.html等不存在的uri會顯⽰default,如果
是⾃定義的狀態碼則會顯⽰在返回數據的狀態碼中,如:
[root@s2 about]# curl --head http://www.pc.com/about/xx.html
HTTP/1.1 489 #489就是⾃定義的狀態返回碼
Server: nginx
Date: Thu, 21 Feb 2019 00:11:40 GMT
Content-Length: 0
Connection: keep-alive
Keep-Alive: timeout=65

長連接配置

  • keepalive_timeout number; #設定保持連接超時時⻓,0表⽰禁⽌⻓連接,默認爲75s,通常配置在http字段作爲站點全局配置 keepalive_requests number; #在⼀次⻓連接上所允許請求的資源的最⼤數量,默認爲100次
keepalive_requests 3;
keepalive_timeout 65 65;
開啓⻓連接後,返回客⼾端的會話保持時間爲60s,單次⻓連接累計請求達到指定次數請求或65秒就會被斷開,後⾯的
60爲發送給客⼾端應答報⽂頭部中顯⽰的超時時間設置爲60s:如不設置客⼾端將不顯⽰超時時間。
Keep-Alive:timeout=60 #瀏覽器收到的服務器返回的報⽂
如果設置爲0表⽰關閉會話保持功能,將如下顯⽰:
Connection:close #瀏覽器收到的服務器返回的報⽂
//使⽤命令測試:
telnet www.magedu.net 80

  Trying 172.18.200.102...
Connected to www.pc.com
Escape character is '^]'.
GET / HTTP/1.1
HOST: www.pc.com

#Response Headers(響應頭信息):
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Thu, 14 Mar 2019 17:23:46 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 14 Mar 2019 14:54:50 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5c8a6b3a-7"
Accept-Ranges: bytes

#⻚⾯內容
pc web

作爲下載服務器配置

//創建所需目錄
mkdir /data/nginx/html/pc/download   #download不需要index.html⽂件

//編輯配置文件
vim /apps/nginx/conf/conf.d/pc.conf

location /download {
autoindex on; #⾃動索引功能
autoindex_exact_size on; #計算⽂件確切⼤⼩(單位bytes),off只顯⽰⼤概⼤⼩(單位kb、mb、
gb)
autoindex_localtime on; #顯⽰本機時間⽽⾮GMT(格林威治)時間
root /data/nginx/html/pc;
}

limit_rate rate; #限制響應給客⼾端的傳輸速率,單位是bytes/second,默認值0表⽰⽆限制
限速與不限速的對⽐:
limit_rate 10k;

#可以使用wget下載資源進行測試下載速度
  • 瀏覽器訪問http://www.pc.com/download/得

在這裏插入圖片描述

作爲上傳服務器配置

client_max_body_size 1m; #設置允許客⼾端上傳單個⽂件的最⼤值,默認值爲1m
client_body_buffer_size size; #⽤於接收每個客⼾端請求報⽂的body部分的緩衝區⼤⼩;默認16k;超出
此⼤⼩時,其將被暫存到磁盤上的由下⾯client_body_temp_path指令所定義的位置
client_body_temp_path path [level1 [level2 [level3]]];
#設定存儲客⼾端請求報⽂的body部分的臨時存儲路徑及⼦⽬錄結構和數量,⽬錄名爲16進制的數字,使⽤hash之後的
值從後往前截取1位、2位、2位作爲⽂件名:
[root@s3 ~]# md5sum /data/nginx/html/pc/index.html
95f6f65f498c74938064851b1bb 96 3d 4 /data/nginx/html/pc/index.html
1級⽬錄佔1位16進制,即2^4=16個⽬錄 0-f
2級⽬錄佔2位16進制,即2^8=256個⽬錄 00-ff
3級⽬錄佔2位16進制,即2^8=256個⽬錄 00-ff
配置⽰例(一般作爲默認配置,所以放置在主配置文件裏):
client_max_body_size 10m;
client_body_buffer_size 16k;
client_body_temp_path /apps/nginx/temp 1 2 2; #reload Nginx會⾃動創建temp⽬錄

其他配置

limit_except

  • 限制客戶端使用除了指定的請求方法之外的其它方法,只能用在location上下文。

在這裏插入圖片描述

  • method:
GET, HEAD, POST, PUT, DELETE

MKCOL, COPY, MOVE, OPTIONS, PROPFIND,

PROPPATCH, LOCK, UNLOCK, PATCH
  • 示例:
limit_except GET HEAD POST {
    deny 192.168.111.200
    allow 192.168.111.0/24;
    deny all;
}
  • 表示除了GET、HEAD、POST方法其他方法都限制,
  • 主機範圍爲:禁止192.168.111.200、允許192.168.111.0/24、禁止所有。
  • 即僅允許192.168.111.0網段訪問,但是禁止192.168.111.200的地址訪問

aio

  • 是否啓用異步I/O功能

在這裏插入圖片描述

  • linux 2.6以上內核提供以下⼏個系統調⽤來⽀持aio:
    • 1、SYS_io_setup:建⽴aio 的context
    • 2、SYS_io_submit: 提交I/O操作請求
    • 3、SYS_io_getevents:獲取已完成的I/O事件
    • 4、SYS_io_cancel:取消I/O操作請求
    • 5、SYS_io_destroy:毀銷aio的context

directio

  • 是否同步寫磁盤
    在這裏插入圖片描述
  • 操作完全和aio相反,aio是讀取⽂件⽽directio是寫⽂件到磁盤
  • 啓⽤直接I/O,默認爲關閉,當⽂件⼤於等於給定⼤⼩時,例如directio 4m,同步(直接)寫磁盤,⽽⾮寫緩存。

open_file_cache

  • 是否緩存打開過的⽂件信息
    在這裏插入圖片描述
  • nginx可以緩存以下三種信息:
    (1) ⽂件元數據:⽂件的描述符、⽂件⼤⼩和最近⼀次的修改時間
    (2) 打開的⽬錄結構
    (3) 沒有找到的或者沒有權限訪問的⽂件的相關信息
  • max=N:可緩存的緩存項上限數量;達到上限後會使⽤LRU(Least recently used,最近最少使⽤)算法實現
    管理
  • inactive=time:緩存項的⾮活動時⻓,在此處指定的時⻓內未被命中的或命中的次數少於
    open_file_cache_min_uses指令所指定的次數的緩存項即爲⾮活動項,將被刪除

open_file_cache_errors

  • 是否緩存查找時發⽣錯誤的⽂件⼀類的信息(默認值爲off)
    在這裏插入圖片描述

open_file_cache_min_uses

  • open_file_cache指令的inactive參數指定的時⻓內,⾄少被命中此處指定的次數⽅可被歸類爲活動項(默認值爲1)
    在這裏插入圖片描述

open_file_cache_valid

  • 緩存項有效性的檢查驗證頻率(默認值爲60s)
    在這裏插入圖片描述
  • 示例
aio                      on;                         # 開啓異步I/O
directio                 4m;                         # 開啓同步磁盤文件大小>4M
open_file_cache          max=1000 inactive=20s;      # 最⼤緩存1000個⽂件,⾮活動數據超時時⻓20s
open_file_cache_valid    30s;                        # 每間隔30s檢查⼀下緩存數據有效性
open_file_cache_min_uses 2;                          # 30秒內⾄少被命中訪問2次才被標記爲活動數據
open_file_cache_errors   on;                         # 緩存錯誤信息
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章