天天看點

第二章 Nginx伺服器的安裝部署22.4、Nginx伺服器基礎配置指令

概述:接着上一節

  • 擷取Nginx伺服器安裝檔案的路徑
  • nginx伺服器安裝部署之前的準備工作
  • Windows平台下nignx伺服器的安裝部署
  • Linux平台下Nignx伺服器的編譯和安裝
  • 認識Nginx伺服器的配置檔案,以及如何進行基本配置
  • 初步學習通過優化Nginx配置,提高Nginx伺服器的性能
  • 展示一個Nginx配置的完整執行個體

2.4、Nginx伺服器基礎配置指令

nginx檔案目錄
nginx安裝檔案目錄
/usr/local/Cellar/nginx
nginx配置檔案目錄
/usr/local/etc/nginx
config檔案目錄
/usr/local/etc/nginx/nginx.conf
系統hosts位置
/private/etc/hosts
Doc Root
/usr/local/var/www
           

2.4.1、nginx.conf 檔案的結構

...            #全局塊
events {
   ...            #events塊
}
http {            # http塊
    ...        #http全局塊
 
    server {        #server塊                        
    ...        #server全局塊
 
        location [PARTERN] {     #location 塊
           
        }
    location [PARTERN] {     #location 塊
           
        }
        
    }
     server {        #server塊                        
    ...        #server全局塊
 
        location [PARTERN] {     #location 塊
           
        }
    location [PARTERN] {     #location 塊
           
        }
        
    }
    ....
}
           

nginx.conf一共由三部分組成,全局塊,events塊和http塊, http塊又包含http全局塊,多個server塊,每個server有包含多個location塊

2.4.1.1、全局塊

全局變量, 通常配置Nginx伺服器的使用者(組)、允許生成的worker process數、Nginx程序PID存放路徑,日志的存放路徑和類型以及配置檔案引入等

2.4.1.2、events塊

指令主要影響Nginx伺服器與使用者的網絡連接配接。常用設定開啟多個工作程序在網絡連接配接進行序列化,是否允許同時接收多個網絡連接配接、事件模型類型、每個工作程序可以同時支援最大連接配接數量

2.4.1.3、http塊

這是重要部分,代理,緩存,日志等

2.4.1.4、server塊

這個與虛拟機有關,每個Server塊就相當于一台虛拟主機

最常見配置 本虛拟主機的監聽配置和本虛拟機主機的名稱或IP配置

2.4.1.5、location塊

一個server可以由多個location塊,location類似Spring mapper映射一樣

示例

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
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;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
    server {
        listen       8080;
        server_name  localhost;
        #charset koi8-r;
        #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$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.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 {
        #    deny  all;
        #}
    }
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    # HTTPS server
    #
    #server {
    #    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;
    #    }
    #}
    include servers/*;
}
           

2.4.2、配置運作Nginx伺服器使用者(組)

文法:

user user [group];

user  :指定可以運作Nginx伺服器的使用者

group  可選項,指定可以運作Nginx伺服器的使用者組

如果希望所有使用者都可以啟動服務

注釋這條語句或者user nobody nobody;   (注意以分号結尾)

2.4.3、配置允許生成的Worker process數

文法: worker-processes number | auto;

number ,指定Nginx程序最多可以産生的Worker process數  (預設值為1)

auto , 設定此值,Nginx程序将自動檢測

2.4.4、配置Nginx程序PID存放路徑

文法:pid file;

file: 指定存放路徑和檔案名稱(預設值将此檔案放置到安裝目錄/logs下,名字為nginx.pid,

例如: pid sbin/web_nginx  (必須到檔案)隻能在全局塊配置

2.4.5、配置錯誤日志的存放路徑

文法:error_log file | stderr [debug | info | notice | warn | error | crit | alert | emerg

error_log logs/error.log error;

2.4.6、配置檔案的引入

include file;   (可以放置到任意位置)

file : 檔案路徑    (注意具有通路權限)

2.4.7、設定網絡連接配接的序列化

accept_mutex on | off;  防止多個程序搶工作,直接序列化配置設定即可 

2.4.8、設定是否允許同時接收多個網絡連接配接

multi_accept on | off;   

2.4.9、 事情驅動模型的選擇

文法:use method  (隻能配置在events塊中)

可選内容有,select、poll、kqueue、epoll、rtsig、/dev/poll 以及 eventport  

2.4.10、配置最大連接配接數

worker_connections number; (隻能event塊中進行配置)

預設值為512

2.4.11、定義MIME-Type

include mime.types

default_type application/octet-stream;   (如果不寫預設是text/plain)

2.4.12、自定義服務日志

全局設定的是軟體運作的日志

服務日志:提供服務的日志,

兩個指令分别是access_log 和log_format指令

文法結構: access_log path[format [buffer=size]];

path: 配置服務日志的檔案存放的路徑和名稱

format:可選項,自定義服務日志的格式字元串,也可以通過log_format設定

size, 配置臨時存放日志的記憶體緩存區大小

這個指令可以配置到http塊、server塊或location塊進行設定

例如:access_log logs/access.log combined; (combined是預設值日志格式字元串)

取消記錄日志功能

access_log off;

文法: log_format name string ..;  (隻能在http塊中配置)

name: 格式字元串的名稱,預設的名字為combined

string: 服務日志的格式字元串。用$引用定義變量,單引号引用結果

log_format exampleLog '$remote_addr - [$time_local] $request ' '$status $body_bytes_sent $http_referer  '  '$http_user_agent'

2.4.13、配置允許sendfile方式傳輸檔案

sendfile on | off; 預設是off (可以在http塊、server塊或者 location塊中進行配置)

sendfile_max_chunk size 分塊的大小

例如: sendfile_max_chunk 128k;

2.4.14、配置使用者連接配接逾時時間

文法: keepalive_timeout timeout[header_timeout];  (可以在http塊,server塊或location塊中配置)

timeout 服務端對連接配接保持的時間,預設值為75s;

header_time ,可選項,在應答封包頭部的keep-alive域設定逾時時間:“Keep-Alive:timeout=header_timeout”

keepalive_timeout 120s 100s;

2.4.15、單連接配接請求數上限

文法:keepalive_requests number; 預設值100, 單次連接配接最多可請求100次

2.4.16、配置網絡監聽

有三種方式:

第一種:listen address[:port]  [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [deferred][accept_filter=filter][bind] [ssl];

第二種:listen port  [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [deferred][accept_filter=filter][bind] [ssl];

第三種:listen unix:path  [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [deferred][accept_filter=filter][bind] [ssl];

address, IP位址,如果是IPv6的位址,需要使用中括号“[]”括起來,比如[fe90::1]等

port:端口号,預設值80端口

path,socket檔案路徑,例如 /var/run/nginx.sock等

default_server, 辨別符,将此虛拟機主機設定為address:port預設主機

setfib+number socket關聯路由表

backlog=number  允許最多多少網絡連接配接同時處于挂起狀态

rcvbuf=size socket 接收緩存區大小

sndbuf=size socket發送緩存區大小

deferred: 将accept()設定為Deferred模式

accept_filter=filter 過濾連接配接

ssl ,辨別符,設定ssl模式進行連接配接

預設配置:

listen  *:80 | *:8000;

listen 192.168.1.10:8000; 監聽具體IP,具體端口的連接配接

listen 192.168.1.10 default_server backlog=1024;(設定具體連接配接請求預設值由此虛拟主機處理,并且允許最多1024網絡連接配接同時處于挂起狀态)

2.4.17、基于名稱的虛拟主機配置

文法:server_name name ...;

多個域名用空格分割

支援通配符

“~”作為正規表達式開頭, “$”作為正規表達式結尾

例如: server_name ~^www\d+\.myserver\.com$;

比對方式優先級:

準确比對server_name

通配符在開始時比對server_name成功

通配符在結尾時比對server_name成功

正規表達式比對server_name成功

2.4.18、基于IP的虛拟主機配置

Linux作業系統支援IP别名添加。配置基于IP的虛拟機,即為Nginx伺服器提供的每台虛拟機配置一個不同的IP,是以需要将網卡設定為同時能夠監聽多個IP位址。

指令:ipconfig 顯示ip配置資訊

添加兩個IP的别名  172.19.238.80 和 172.19.238.81

#ifconfig eth0:0  172.19.238.80 netmask 255.255.240.0 up

#ifconfig eth0:1  172.19.238.81 netmask 255.255.240.0 up

如上方法設定系統重新開機之後将不予儲存,需要重新配置,為了完成一勞永逸

# echo "ifconfig eth0:0  172.19.238.80 netmask 255.255.240.0 up"   >> /etc/rc.local

# echo "ifconfig eth0:1  172.19.238.81 netmask 255.255.240.0 up" >> /etc/rc.local

...

http {

   ...

    server {

        listen       80;

        server_name  172.19.238.80;

       ...

    }

      server {

        listen       80;

        server_name  172.19.238.81;

       ...

    }

    ...

}

2.4.19 配置location塊

文法結構: location [= | ~ | ~* | ^~] uri {....}

uri 變量是待比對的請求字元串

“=”  用于标準uri前(不含正規表達式)

“~”, 用于表示正規表達式,并且區分大小寫

"~*", 用于表示uri包含正規表達式,并且不區分大小寫

“^~” 用于标準uri前

2.4.20、配置請求的根目錄

文法: root path;

path 為Nginx伺服器接收到請求以後查找資源的根目錄路徑。Path是預設變量, $document_root($符号引用)

例如

location /data/

{

    root /locationtest1;

}

2.4.21、更改location的URI

文法: alias  path;

例子:

location ~ ^/data/(.+\.(htm|htm))$

{

    alias /locationtest1/other/$1;

}

2.4.22、設定網站的預設首頁

文法: index  file ...; 預設值index.html

location ~ ^/data/(.+)/web/ $

{

    index index.$1.html index.my1.html index.html;

}

當location收到"/data/locationtest/web"    那麼$1 = “locationtest”

2.4.23、設定網站的錯誤頁面

一般來說, HTTP 2XX 代表請求正常完成, HTTP3XX代表網站重定向, HTTP4XX代表用戶端出現錯誤, HTTP 5XX代表伺服器出現錯誤。

文法: error_page  code ... [=[response]] uri

code 要處理HTTP錯誤代碼

response 可選項将code指定的錯誤代碼轉化為新的錯誤代碼reponse

uri  錯誤頁面的路徑或者網址 ,如果是路徑是以nginx安裝路徑下html目錄為根目錄的相對目錄

例如:

error_page 404 /404.html

error_page 403 http://somewebsite.com/forbidden.html;

希望nginx服務使用 "/myserver/errorpages/404.html" 頁面響應404錯誤

error_page 404 / 404.html

之後添加location塊

location /404.html

{

    root /myserver/errorpages/          //重定向這個目錄下

}

2.4.24、基于IP配置Nginx的通路權限

Nginx配置通過兩種支援基本通路權限的控制,其中一種有HTTP标準子產品ngx_http_access_module 支援的,通過IP來判斷用戶端是否擁有對Nginx的通路權限

allow address | CIDR | all;

address 允許通路的用戶端IP,不允許同時設定多個,設定多個,使用多條allow指令

CIDR  允許通路的用戶端的CIDR位址。 主機/端口, 201.80.12.20/80

all   代表允許所有用戶端通路

現在也支援IPv6位址

另個指令deny  ,禁止通路Nginx的用戶端IP

文法:deny  address | CIDR | all;   

兩個指令可以在http塊、server塊或者location塊中配置

注意all用法

location / {

  deny 192.168.1.1;

  allow  192.168.1.0/24;

  deny all;

}

這是允許通路 allow  192.168.1.0/24; 原則是隻要一個說允許就是允許的。

2.4.25、基于密碼配置Nginx的通路權限

Nginx還支援基于HTTPBasic Authentication協定認證,用于識别使用者名和密碼

由HTTP 标準子產品ngx_http_auth_basic_module支援

auth_basic 指令,用于開啟或關閉驗證功能

文法:auth_basic string | off;

string  開啟該認證,并配置驗證時的訓示資訊

off, 關閉認證功能

auth_basic_user_file 指令, 用于設定包含使用者名和密碼資訊的檔案路徑

文法: auth_basic_user_file file ;

file為檔案的絕對路徑

密碼檔案支援明文或者密文

明文的格式:

name1:password1

name2:password2:comment

name3:password3

加密可以使用crypt()函數, 或者htpasswd指令生成。

如果沒有htpasswd指令,需要安裝httpd

# yum install -y httpd

開始生成密碼檔案

# htpasswd -c -d /home/Nginx_123/nginx/conf/pass_file username

2.5、Nginx伺服器基本配置執行個體

###全局塊 開始  #####

user nobody nobody;       #配置允許運作Nginx伺服器的使用者和使用者組

worker_processes 3;       #配置允許Nginx程序生成的Worker processes數

error_log  logs/error.log;  #配置Nginx伺服器運作時錯誤日志存放路徑

pid  nginx.pid;          # 配置Nginx伺服器運作時的pid檔案存放路徑和名稱

###全局塊 結束 ####

####events 塊 開始 ####

events {

   use epoll;   # 配置事件驅動模型

   worker_connections  1024;  #配置最大連接配接數量

}

### events塊 結束  ###

### http 塊 開始 ####

http {

   include  mime.types;   # 定義MIME-Type

   default_type application/octet-stream;  

   sendfile on;            #配置允許使用sendfile方式傳輸

   keepalive_timeout 65;   #配置連接配接逾時時間

   log_format access.log '$remote_addr-[$time_local]-"$request"-"$http_user_agent"';

   #### server 塊 開始 ####

   ##配置 虛拟主機 myserver1

   server{

    listen 8081;  # 配置監聽端口和主機名稱(基于名稱)

    server_name myServer1;

    access_log  /myweb/server1/log/access.log; #配置請求處理日志存放路徑

    error_page 404 /404.html; # 配置錯誤頁面

    location /server1/location1 {   # 配置處理/server1/location1請求的location

        root /myweb;

        index index.svr1-locl.htm;

    }

    location /server1/location2 {   # 配置處理/server1/location2請求的location

        root /myweb;

        index index.svr1-loc2.htm;

    }

   }

   ##配置 虛拟主機 myserver2

   server{

    listen 8082;  # 配置監聽端口和主機IP(基于IP)

    server_name 192.168.1.2;

    access_log  /myweb/server2/log/access.log; #配置請求處理日志存放路徑

    error_page 404 /404.html; # 配置錯誤頁面

    location /server2/location1 {   # 配置處理/server2/location1請求的location

        root /myweb;

        index index.svr2-locl.htm;

    }

    location /svr2/loc2 {   # 配置location的URI進行更改

        alias /myweb/server2/location2/;

        index index.svr2-loc2.htm;

    }

    location = /404.html {

       root /myweb/;

       index 404.html;

    }

   }

   #### server塊  結束 ####

}

#### http 塊 結束 ####

摘自 《Nginx高性能Web伺服器詳解》

文法: auth_basic_user_file file ;

file為檔案的絕對路徑

密碼檔案支援明文或者密文

明文的格式:

繼續閱讀