1. 程式人生 > >Nginx安裝配置

Nginx安裝配置

nginx安裝 配置

Nginx的基本架構:

master/worker

一個master進程,可生成一個或多個worker進程;

master:加載配置文件、管理worker進程、平滑升級……

worker:如果是http請求:提供http服務、http代理、fastCGI代理

事件驅動:epoll(Linux), kqueue(FreeBSD), /dev/poll(Solaris)

消息通知:select, poll, rt signals

支持sendfile, sendfile64

支持AIO,mmap

master: 只有一個,作用:加載配置文件、管理worker進程、平滑升級,...

worker:http服務,http代理,fastcgi代理,...

cache loader:緩存加載

cache manager:緩存管理

模塊類別:

核心模塊:core module

標準模塊:

Standard HTTP modules 標準模塊

Optional HTTP modules 可選模塊

Mail modules 郵件模塊

3 rd part modules 第三方模塊

nginx用來做什麽:

靜態資源的web服務器

http協議反向代理


nginx安裝配置

準備開發環境:

yum group install -y "development tools" "server platform delvelopment"

yum -y install openssl-devel pcre-devel zlib-devel

安裝:

[root@promote nginx-1.8.1]# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx/nginx.id --lock-path=/var/lock/nginx.lock --with-http_ssl_module --with-http_gzip_static_module --with-debug --with-http_stub_status_module

[root@promote nginx-1.8.1]#make && make -j4 install

命令幫助:

[root@promote nginx]# /usr/local/nginx/sbin/nginx -h

nginx version: nginx/1.8.1

Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]


Options:

-?,-h : this help

-v : show version and exit

-V : show version and configure options then exit

-t : test configuration and exit

-q : suppress non-error messages during configuration testing

-s signal : send signal to a master process: stop, quit, reopen, reload

-p prefix : set prefix path (default: /usr/local/nginx/)

-c filename : set configuration file (default: /etc/nginx/nginx.conf)

-g directives : set global directives out of configuration file

啟動服務:

[root@promote nginx]# /usr/local/nginx/sbin/nginx

查看服務:

[root@promote nginx]# ps aux |grep nginx

root 38371 0.0 0.1 45788 1112 ? Ss 15:12 0:00 nginx: master process /usr/local/nginx/sbin/nginx

nginx 38372 0.0 0.2 48320 2212 ? S 15:12 0:00 nginx: worker process

root 38984 0.0 0.0 112680 972 pts/1 D+ 15:17 0:00 grep --color=auto nginx

配置文件的組成部分:

主配置文件:nginx.conf

include conf.d/*.conf

fastcgi,scgi,uwscgi的相關配置

mime.types

配置指令(必須以分號結尾)

directive value [value1] [value2]……

支持使用變量:

內置變量:由模塊引入,可直接引用

自定義變量:set variable_name value

引用變量:$variable_name

配置文件組織結構

main blokc:全局配置

event{ 事件驅動的相關配置

……

}

mail{ 郵件服務的相關配置

……

}

http相關的配置:

http{

……

……

server{

……

server_name 當前域名

root 指明根文檔路徑

alias

location /uri/{ 當訪問該uri時的專用配置

……

}

……

}

server{

……

……

}

}

#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; 最大並發量

}

main block(main 配置段):

配置指令的類別:

1、 正常運行務必的配置

2、 優化性能的配置

3、 用於調試、定位問題的配置

正常運行必務的配置:

1、 user USERNAME [GROUPNAME]; 指定用於運行worker進程的用戶和組,組可省略。

如: user nginx nginx

2、 pid /PATH/TO/PID_FILE;指明nginx進程的pid文件路徑

如:pid /var/run/nginx.pid;

3、 worker_rlimit_nofile # :指定一個worker進程所能夠打開的最大文件描述符數量


性能優化相關的配置

1、 worker_processes number|auto;


The optimal value depends on many factors including (but not limited to) the number of CPU cores, the number of hard disk drives that store data, and load pattern. When one is in doubt, setting it to the number of available CPU cores would be a good start (the value “auto” will try to autodetect it).

worker的進程數;通常應該為CPU的核心數減1;可以為"auto",實現自動設定(設定值為CPU核心數量)

2、 Syntax: worker_cpu_affinity cpumask ...;

worker_cpu_affinity auto [cpumask];

Default:

Context: main

Binds worker processes to the sets of CPUs. Each CPU set is represented by a bitmask of allowed CPUs. There should be a separate set defined for each of the worker processes. By default, worker processes are not bound to any specific CPUs.

worker_processes 4;

worker_cpu_affinity 0001(第0顆CPU) 0010 (第1顆)0100(第2顆) 1000(第3顆)

EX:

worker_processes 2;

worker_cpu_affinity 0010 0100;

3、 Syntax: worker_priority number; 指明進程優先級

Default: worker_priority 0;

Context: main

number範圍:[-20,19] ,代表數值:100-139

Defines the scheduling priority for worker processes like it is done by the nice command: a negative number means higher priority. Allowed range normally varies from -20 to 20.

調試、定位問題:

1、 daemon on | off;

Default:daemon on

Context: main

是否以守護進程方式啟動nginx進程

2、 master_process on | off;

Default: master_process on

是否以master/worker模型啟動nginx進程;

3、 error_log file_ [level];

Default: error_log logs/error.log error;

Context: main, http, mail, stream, server, location

錯誤日誌文件及其級別;出於調試的需要,可以設定為debug;但 方式:

file /PATH/TO/SOME_LOG_FILE

stderr:發送到錯誤輸出

syslog:serer=address[,paravmeter=value]:發送到syslog服務器

memory:size

日誌級別:debug, info, notice, warn, error, crit, alert, or emerg.

debug僅在編譯時使用了“--with-debug”選項時才有效;


nginx.conf:

main block

event{

....

}

1、 Syntax: worker_connections number; 每個worker進程所能夠並發打開的最大連接數。最大並發響應數

Default: worker_connections 512; number不能比worker_rlimit_nofile大

Context: events 只能用在events中

Sets the maximum number of simultaneous connections that can be opened by a worker process.


It should be kept in mind that this number includes all connections (e.g. connections with proxied servers, among others), not only connections with clients. Another consideration is that the actual number of simultaneous connections cannot exceed the current limit on the maximum number of open files, which can be changed by worker_rlimit_nofile.


當前系統能響應的最大並發數量:worker_proccesses*worker_connections

2、 Syntax: use method; 並發連接請求處理時使用的方法

Default:

Context: events

Specifies the connection processing method to use. There is normally no need to specify it explicitly, because nginx will by default use the most efficient method.

linux系統只有一種:use epoll;

默認開啟

3、 Syntax: accept_mutex on | off

Default: accept_mutex off;

Context: events

If accept_mutex is enabled, worker processes will accept new connections by turn. Otherwise, all worker processes will be notified about new connections, and if volume of new connections is low, some of the worker processes may just waste system resources.

There is no need to enable accept_mutex on systems that support the EPOLLEXCLUSIVE flag (1.11.3) or when using reuseport.

Prior to version 1.11.3, the default value was on.

各worker接收用戶的請求的負載均衡鎖;啟用時,表示用於讓多個worker輪流地、序列化地響應新請求。

在各worker之間負載均衡的機制

默認開啟

#4、 Syntax: lock_file file;

# Default: lock_file logs/nginx.lock;

# Context: main

#nginx uses the locking mechanism to implement accept_mutex and serialize access to shared memory. On most #systems the locks are implemented using atomic operations, and this directive is ignored. On other systems the “lock #file” mechanism is used. This directive specifies a prefix for the names of lock files.


http {

...

}


定義套接字相關功能

1、 Syntax: server { ... } 配置一個虛擬主機

Default:

Context: http

配置方法:

server{

listen PORT;

server_name HOSTNAME;

root /PATH/TO/DOCUMENTROOT;

....

}

註意:

1)、基於port的虛擬主機,listen指令要使用不同的端口

2)、基於Hostname的虛擬主機,server_name指令指向不同的主機名

3)、基於IP的虛擬主機,listen IP:PORT;


2、

Syntax: listen address[:port] [default_server] [ssl] [http2 | spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen port [default_server] [ssl] [http2 | spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen unix:path [default_server] [ssl] [http2 | spdy] [proxy_protocol] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

Default: listen *:80 | *:8000;

Context: server

ets the address and port for IP, or the path for a UNIX-domain socket on which the server will accept requests. Both address and port, or only address or only port can be specified. An address may also be a hostname, for example:

UNIX-domain sockets (0.8.21) are specified with the “unix:” prefix:

listen unix:/var/run/nginx.sock;


listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size]接收緩沖大小[sndbuf=size]發送緩存大小

可用地址的所有端口

listen port [default_server] [ssl] [http2 | spdy]


listen unix:path [default_server] [ssl] [http2 | spdy]

unix sock機制:客戶端和服務端是同一臺電腦時,不通過客戶端數據加應用層首部-->加端口首部-->加IP首部-->發送給服務端。而是直接在內存中找一段空間,把數據發送到內存,服務端直接從內存中讀取數據;響應時,服務端把數據發送到內存,客戶端直接從內存讀取數據。節省資源。

default_server:設置默認主機

ssl:限制只能通過ssl連接提供服務

backlog:後援隊列的長度

rcvbuf:接收緩沖區大小

sndbuf:發送緩沖區大小

3、 Syntax: server_name name ...; 指明當前server的主機名

Default: server_name "";

Context: server

指明當前server的主機名;後跟一個或空白字符分隔的多個主機;

支持使用*任意長度的任意字符

支持~起始的正則表達式模式字符串

應用策略:

1、 首先精確匹配 www.magedu.com

2、 左側*通配符匹配 *.magedu.com

3、 右側*通配符匹配 www.magedu.*

4、 正則表達式模式匹配 ~^.*\.magedu\.com$

4、 Syntax: tcp_nodelay on | off;

Default: tcp_nodelay on;

Context: http, server, location

Enables or disables the use of the TCP_NODELAY option. The option is enabled only when a connection is transitioned into the keep-alive state.

對keepalived模式下的連接是否啟用TCP_NODELAY選項

delay:將多個較小的數據塊合並成一個大的數據塊後發送

開啟可提高數據的實時傳輸,但是會浪費帶寬資源。關閉會節省帶寬,但是數據傳輸的實時性會受影響。

5、 Syntax: tcp_nopush on | off;

Default: tcp_nopush off;

Context: http, server, location

Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or the TCP_CORK socket option on Linux. The options are enabled only when sendfile is used. Enabling the option allows


sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.*;

sending a file in full packets.

6、 Syntax: sendfile on | off;

Default: sendfile off;

Context: http, server, location, if in location

Enables or disables the use of sendfile().

直接在內核中封裝響應報文,響應用戶請求。默認關閉。

定義路徑相關的配置

7、 root Sets the root directory for requests. 設置web資源路徑映射;用於指明請求的URL所對應的文檔的目錄路徑

Syntax: root path;

Default: root html;

Context: http, server, location, if in location

EXP:

location /i/ {

root /data/w3;

}

8、 location:根據用戶請求的URI來匹配定義的location,匹配到時,此請求將被相應的location塊中的配置所處理。隱藏有if的意思。

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

location @name { ... }

Default:

Context: server, location

EXP:

server{

...

location / {

...

}

location {

....

}

=:URI的精確匹配

~:做正則表達式模式匹配,區分字符大小寫

~*:做正則表達式模式匹配,不區分字符大小寫

^~:URI的左半部分模式匹配,不區分字符大小寫

匹配優先級:精確匹配=、^~、~或~*、以上四種模式不帶符號的URL

9、 alias 定義路徑別名,文檔映射的一種機制。僅用於location上下文

Syntax: alias path;

Default:

Context: location

location /images/ {

root /data/imgs/;

}


location /images/ {

alias /data/imgs/;

}

註意:

root指令:給定的路徑對應於location中的/url/左側的/;

/images/test.jpg --> /data/imgs/images/test.jpg

alias指令:給定的路徑對應於location中的/url/右側的/;

/images/test.jpg --> /data/imgs/test.jpg

10、index 設置默認主頁

Syntax: index file ...;

Default: index index.html;

Context: http, server, location

用在http中,對所有server生效。用在server中,只對當前server生效。用在location中,只對當前Location有效

11、error_page 自定義錯誤頁,根據用戶請求的資源的http響應的狀態碼實現錯誤頁重定向

Syntax: error_page code ... [=[response]] uri;

Default:

Context: http, server, location, if in location

根據http的狀態碼重定向錯誤頁面;

error_page 404 /404.html

error_page 404 =200 /404.html (以指定的響應狀態碼進行響應)

12、try_files

Syntax: try_files file ... uri;

try_files file ... =code;

Default:

Context: server, location

定義客戶端請求的相關配置

13、keepalive_timeout 設定keepalive連接的超時時長;0表示禁止長連接;默認為75s;

Syntax: keepalive_timeout timeout [header_timeout];

Default: keepalive_timeout 75s;

Context: http, server, location

14、keepalive_requests 在keepalived連接上所允許請求的最大資源數量;默認為100

Syntax: keepalive_requests number;

Default: keepalive_requests 100;

Context: http, server, location

This directive appeared in version 0.8.0.

15、keepalive_disable 指明禁止為何種瀏覽器使用keepalive功能

Syntax: keepalive_disable none | browser ...;

Default: keepalive_disable msie6;

Context: http, server, location

16、send_timeout 向客戶端發送響應報文的超時時長(指兩次寫操作之間的間隔時長),默認為60s

Syntax: send_timeout time;

Default: send_timeout 60s;

Context: http, server, location

17、client_body_buffer_size

接收客戶請求報文body的緩沖區大小;默認為16k;超出此大小時,其將被暫存於磁盤上

Syntax: client_body_buffer_size size;

Default: client_body_buffer_size 8k|16k;

Context: http, server, location

18、client_body_temp_path 設定用於存儲客戶端請求報文body部分的臨時存儲路徑及子目錄結構和數量

Syntax: client_body_temp_path path [level1 [level2 [level3]]];

Default: client_body_temp_path client_body_temp;

Context: http, server, location


Defines a directory for storing temporary files holding client request bodies. Up to three-level subdirectory hierarchy can be used under the specified directory. For example, in the following configuration


client_body_temp_path /spool/nginx/client_temp 1 2;

a path to a temporary file might look like this:


/spool/nginx/client_temp/7/45/00000123457

19、limit_rate 限制客戶端每秒鐘所能夠傳輸的字節數,默認為0表示無限制

Syntax: limit_rate rate;

Default: limit_rate 0;

Context: http, server, location, if in location

EXP:

配置文件server段中增加以下內容:

location /download {

limit_rate 20480;

root /web/host1;

}

創建試驗文件:

[root@promote nginx]# dd if=/dev/zero of=/web/host1/download/test.img bs=1M count=50

記錄了50+0 的讀入

記錄了50+0 的寫出

52428800字節(52 MB)已復制,0.454343 秒,115 MB/秒

創建試驗用目錄:

[root@promote nginx]# tree /web

/web

├── host1

│ ├── 404.html

│ ├── download

│ │ ├── download.html

│ │ └── test.img

從另一主機下載該試驗文件做測試:

[root@localhost nginx]# wget www.lxk.com/download/test.img

--2017-09-24 08:01:56-- http://www.lxk.com/download/test.img

Resolving www.lxk.com (www.lxk.com)... 192.168.2.234

Connecting to www.lxk.com (www.lxk.com)|192.168.2.234|:80... connected.

HTTP request sent, awaiting response... 200 OK

Length: 52428800 (50M) [application/octet-stream]

Saving to: ‘test.img.5’


0% [ ] 122,880 20.1KB/s eta 42m 23s


對客戶的請求進行限制的相關配置


20、limit_except 限制對指定請求方法之外的其它方法的使用客戶端

Syntax: limit_except method ... { ... }

Default:

Context: location

EXP:

limit_except GET {

allow 192.168.1.0/32;

deny all;

}

實例:除了GET和POST之外的其它方法僅允許192.168.2.154使用

location /download {

limit_except GET {

allow 192.168.2.154;

deny all;

}

root /web/host1;

}


文件操作優化相關的配置

21、aio 異步傳輸功能

Syntax: aio on | off | threads[=pool];

Default: aio off;

Context: http, server, location

This directive appeared in version 0.8.11.

Exp:

Enables or disables the use of asynchronous file I/O (AIO) on FreeBSD and Linux:


location /video/ {

aio on;

output_buffers 1 64k; 緩存池大小

}

22、directio 設定直接IO的大小或者關閉直接IO。

IO寫請求的時候,數據不在內存中緩存而是直接刷到直接磁盤上。

數據的可靠性比較高,對性能有影響。

Syntax: directio size | off;

Default: directio off;

Context: http, server, location

This directive appeared in version 0.7.7.

23、open_file_cache

Syntax: open_file_cache off;

open_file_cache max=N [inactive=time];

Default: open_file_cache off;

Context: http, server, location

max=N緩存條目的上限,達到上限後,根據LRU算法(最近最少使用),刪除相應緩存條目。

inactive=time:緩存項的超時時長。在此處指定的時長內沒有被訪問過的緩存項是為非活動緩存項,因此直接刪除

nginx可以緩存以下三種信息提高性能:

1)、文件的描述符、文件大小和最近一次的修改時間

2)、打開的目錄的結構

3)、沒有找到的文件或者沒有權限訪問的文件的相關信息

24、open_file_cache_errors Enables or disables caching of file lookup errors by open_file_cache.

是否緩存查找時發生錯誤的文件一類的信息

Syntax: open_file_cache_errors on | off;

Default: open_file_cache_errors off;

Context: http, server, location

25、open_file_cache_min_uses 在open_file_cache指令的inactive參數指定的時長內,至少訪問此處指定的次數,方可被歸類到非活動項。

Sets the minimum number of file accesses during the period configured by the inactive parameter of the open_file_cache directive, required for a file descriptor to remain open in the cache.

Syntax: open_file_cache_min_uses number;

Default: open_file_cache_min_uses 1;

Context: http, server, location

26、open_file_cache_valid Sets a time after which open_file_cache elements should be validated.

多長時間檢查一次open_file_cache中緩存項是否為非活動項

Syntax: open_file_cache_valid time;

Default: open_file_cache_valid 60s;

Context: http, server, location


ngx_http_access_module 實現基於IP的訪問控制

27、Syntax: allow address | CIDR | unix: | all;

Default:

Context: http, server, location, limit_except

Allows access for the specified network or address. If the special value unix: is specified (1.5.1), allows access for all UNIX-domain sockets.


28、Syntax: deny address | CIDR | unix: | all;

Default:

Context: http, server, location, limit_except

Denies access for the specified network or address. If the special value unix: is specified (1.5.1), denies access for all UNIX-domain sockets.

ngx_http_auth_basic_module

29、auth_basic 使用basic機制進行用戶認證

Syntax: auth_basic string | off; string:

Default: auth_basic off;

Context: http, server, location, limit_except

30、auth_basic_user_file 使用basic機制認證時,認證文件存放位置

Syntax: auth_basic_user_file file;

Default:

Context: http, server, location, limit_except

文件格式:

name1:password1

name2:password2:comment

密碼格式:

htpasswd命令

EXP:

[root@promote nginx]# htpasswd -c -m /etc/nginx/.nginxpasswd tom

New password:

Re-type new password:

Adding password for user tom

[root@promote nginx]# htpasswd -m /etc/nginx/.nginxpasswd lxk

New password:

Re-type new password:

Adding password for user lxk

[root@promote nginx]# vim /web/host1/admin/index.html

主配置文件中增加以下內容:

location /admin/ {

auth_basic "Admin Area";

auth_basic_user_file /etc/nginx/.nginxpasswd;

root /web/host1;

}

ngx_http_stub_status_module 輸出nginx的基本狀態信息 重要

The ngx_http_stub_status_module module provides access to basic status information.

31、Syntax: stub_status;

Default:

Context: server, location

EXP:

location /basic_status {

stub_status;

}

狀態頁面顯示以下內容:

Active connections: 2

server accepts handled requests

81 81 102

Reading: 0 Writing: 1 Waiting: 1

Active connections:處於活動狀態的客戶端連接的數量

accepts:已經接受的客戶端連接總數量

handled:已經處理過後客戶端連接總數量

requests:客戶端的總的請求數量

Readking:處於讀取的客戶端請求報文首部的數量

Writing:處於向客戶端發送響應報文首部的連接數量

Waiting:處於等待客戶端發出請求的空閑連接數量

ngx_http_referer_module

32、referer_hash_bucket_size

The ngx_http_referer_module module is used to block access to a site for requests with invalid values in the “Referer” header field.

Syntax: valid_referers none | blocked | server_names | string ...;

Default:

Context: server, location

none 請求報文首部沒有referer首部

the “Referer” field is missing in the request header;

blocked 請求報文的referer首部沒有值

the “Referer” field is present in the request header, but its value has been deleted by a firewall or proxy server; such values are strings that do not start with “http://” or “https://”;

server_names 其值是主機名

the “Referer” request header field contains one of the server names;

arbitrary string 直接字符串,可以使用*作為通配符

defines a server name and an optional URI prefix. A server name can have an “*” at the beginning or end. During the checking, the server’s port in the “Referer” field is ignored;

regular expression 被指定的正則表達式模式匹配到的字符串,要使用~開頭

the first symbol should be a “~”. It should be noted that an expression will be matched against the text starting after the “http://” or “https://”.

Example:


valid_referers none blocked server_names

*.example.com example.* www.example.org/galleries/

~\.google\.;

valid_referers none blocked server_names *.example.com example.* www.example.org/galleries/ ~\.google\.;

if ($invalid_referer) {

return 403;

}


Nginx安裝配置