Untitled


nginx 介绍

  Nginx (“engine x”) 是一个自由、开源、高性能的HTTP和反向代理服务器( 作为HTTP, SMTP,POP3 和 IMAP反向代理服务器),该软件由 Igor Sysoev 创建,并于2004年首次公开发布。Nginx选择高性能的 epoll作为网络I/O模型,在高并发连接的情况下,Nginx 是 Apache 服务器不错的替代品,它能够支持高达 50000 个并发连接数的相应,而内存、CPU等资源消耗却非常低,运行非常稳定,解决了著名的C10K问题。中国大陆使用nginx或基于其做二次开发的网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。


nginx 安装


一、rpm包安装

  1. rpm包下载地址

  2. 安装
    此处使用官网的yum源安装
    配置yum仓库

[12@root yum.repos.d]# cat nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

  安装

yum -y install nginx


二、源码编译安装

  1. 源码包下载地址
    http://nginx.org/en/download.html

  2. 通过修改源码来自定义响应头部 Server 字段显示的名称和版本号。

[21@root src]# pwd
/usr/src
[21@root src]# ls
nginx-1.13.5.tar.gz
[21@root src]# tar -xf nginx-1.13.5.tar.gz
[21@root src]# cd nginx-1.13.5/
# 修改当设置了 "server_tokens off;" 时显示的软件名称
[21@root nginx-1.13.5]# vim src/http/ngx_http_header_filter_module.c
static u_char ngx_http_server_string[] = "Server: engine" CRLF;
# 修改未设置了 "server_tokens off;" 时显示的软件名称和版本号
[21@root nginx-1.13.5]# vim src/core/nginx.h
#define nginx_version 1020001
#define NGINX_VERSION "1.20.1"
#define NGINX_VER "zhuenginx/" NGINX_VERSION
  1. 创建nginx账户,并安装依赖软件
# 创建用户
[21@root nginx-1.13.5]# useradd -s /sbin/nologin -r nginx
# 安装依赖包
[21@root nginx-1.13.5]# yum -y install openssl-devel pcre-devel
# 创建MakeFile文件
./configure \
--prefix=/usr/share/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 \ #http日志文件路径
--http-client-body-temp-path=/var/lib/nginx/tmp/client_body \ #客户端主体文件临时存放路径
--http-proxy-temp-path=/var/lib/nginx/tmp/proxy \ #http反向代理服务器响应报文临时文件存放路径
--http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi \ #FastCGI反向代理服务器响应报文临时文件存放路径
--pid-path=/run/nginx.pid \ #pid文件路径
--lock-path=/run/lock/subsys/nginx \ #锁文件路径
--user=nginx \ #wroker进程发起者用户名
--group=nginx \ #wroker进程发起者组名
--with-file-aio \ #文件异步存储模块
--with-http_gunzip_module \ #gunzip压缩模块
--with-http_gzip_static_module \ #gzip压缩模块
--with-http_stub_status_module \ #服务器信息显示模块
--with-pcre \ #支持正则匹配模块
--with-stream=dynamic \
--with-stream_ssl_module \
--with-debug
# 编译安装
[21@root nginx-1.13.5]# make && make install


三、启动 nginx

  1. 运行 nginx
nginx
  1. 重载配置文件
nginx -s reload
  1. 检查配置文件语法
nginx -t
  1. 停止 nginx
nginx -s stop


nginx 配置文件结构

/etc/nginx/nginx.conf

Alt text


nginx 配置


一、正常运行必备的配置

  1. 修改worker进程的用户名和组名
Syntax: user user [group];
Default: user nobody nobody;
Context: main
  1. master进程的pid文件路径
Syntax: pid file;
Default: pid nginx.pid;
Context: main
  1. 导入其它子配置文件
Syntax: include file | mask;
Default: —
Context: any
# example
include /etc/nginx/default.d/*.conf;
  1. 加载模块
Syntax: load_module file;
Default: —
Context: main
# example
load_module "/usr/lib64/nginx/modules/ngx_stream_module.so";


二、性能优化相关的配置

  1. 设定worker进程数量,通常为当前主机CUP核心数
Syntax: worker_processes number | auto;
Default: worker_processes 1;
Context: main
  1. worker进程与CPU核心绑定,提高CPU缓存命中率
Syntax: worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default:
Context: main
# example
# 1. 4颗CPU,启动4个worker进程,将每个进程分别与CPU0, CPU1, CPU2, CPU3绑定
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
# 2. 4颗CPU,启动2个worker进程,第一个进程绑定到CPU0/CPU2上,第二个进程绑定到CPU1/CPU3上
worker_process 2;
worker_cpu_affinity 0101 1010;
# 3. 自动绑定
worker_process auto;
worker_cpu_affinity auto;
  1. 设定worker进程的优先级(nice值),nice值范围为[-20,19]
Syntax: worker_priority number;
Default: worker_priority 0;
Context: main
# example
worker_priority -10
  1. 指定worker进程打开的最大文件数量
Syntax: worker_rlimit_nofile number;
Default: —
Context: main
# example
worker_rlimit_nofile 30000


三、事件驱动相关的配置

events {
...
}
  1. 每个worker进程所能打开的最大并发连接数量,worker_connections设定的数值不能大于另外一个指令worker_rlimit_nofile number (worker进程最大打开文件数)所设定的值
Syntax: worker_connections number;
Default: worker_connections 1024;
Context: events
  1. 指明并发连接请求的处理方法,一般不需要指定,nginx会使用最有效的连接处理方法。
Syntax: use method;
Default: —
Context: events
# example
use epoll
  1. 处理新连接请求的方式,accept_mutexon时,有新的连接请求,worker进程轮流处理,否则将通知所有进程,造成”惊群”,效率低下。
Syntax: accept_mutex on | off;
Default: accept_mutex off;
Context: events
# example
accept_mutex on;


四、调试和定位问题

  1. 是否以守护进程方式运行nginx,设定为 on 将在后台以守护进程方式运行nginx,否则在前台运行。
Syntax: daemon on | off;
Default: daemon on;
Context: main
  1. 是否以master/worker模式运行nginx
Syntax: master_process on | off;
Default: master_process on;
Context: main

master_process 为 on 时,nginx会启动一个master主进程,master主进程fork()出一个或多个worker子进程,此种情况下makster进程充当监控程序,通过信号通知worker进程处理用户的连接请求。若设定为 off,master进程将自己处理所有业务。

Alt text

  1. 错误日志文件路径及错误级别,错误级别按严重级别顺序排序为: debug, info, notice, warn, error, crit, alert, emerg,指定某错误级别后,该级别及更严重级别的消息将记录于错误日志中。
Syntax: error_log file [level];
Default: error_log logs/error.log error;
Context: main, http, mail, stream, server, location
# example
error_log /var/log/nginx/error.log error;


五、http协议配置段格式

http
{
... ...
server
{
... ...
location [ = | ~ | ~* | ^~ ] uri
{
... ...
}
}
server
{
... ...
}
}


六、与套接字相关配置

  1. nginx主机(或虚拟主机)监听的套接字(IP地址,端口,UNIX套接字)
Syntax: listen {address[:port]|port|unix:path} [default_server] [ssl] [backlog=number] [rcvbuf=size] [sndbuf=size];
Default: listen *:80 | *:8000;
Context: server
---
default_server #设定为默认虚拟主机
ssl #限制必须通过ssl连接才提供服务
backlog=number #超过最大并发连接数后,设定新请求进入队列的最大值
rcvbuf=size #接收缓冲区的大小
sendbuf=size #发送缓冲区的大小
# example
listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;
listen unix:/var/run/nginx.sock;
listen 127.0.0.1:8000 default_server;
  1. nginx主机(或虚拟主机)的主机名
Syntax: server_name name ...;
Default: server_name "";
Context: server
---
1. 支持 “*” 通配符
*.zhubiaook.com www.zhubiaook.*
2. 支持正则表达, 要使用正则匹配,在模式前加符号“~”
~^www\d+\.zhubiaook\.com$
3. 各种模式的优先级
精确匹配 www.zhubiaook.com
左侧通配符 : *.zhubiaook.com
右侧通配符 : www.zhubiaook.com
正则表达式 : ~^www\d+\.zhubiaook\.com$
default_server : 均为匹配到以上主机名,则使用默认监听套接字的虚拟主机
# example
server {
server_name zhubiaook.com www.zhubiaook.com;
}
server {
server_name *.zhubiaook.com www.zhubiaook.*;
}
server {
server_name www.zhubiaook.com ~^www\d+\.zhubiaook\.com$;
}
  1. 设定站点的根目录
Syntax: root path;
Default: root html;
Context: http, server, location, if in location
# example
http
{
# 所有主机默认的主站点目录
root /app/web
server
{
# 特定主机的主站点目录
root /data/html
location /images/ {
# uri为/images/时的主站点目录:/images/picture/
root /picture
}
}
}
  1. 设定虚拟主机
    基于域名的虚拟主机
[11@root conf.d]# cat virtual.conf
# A virtual host using of name-based configuration
server {
listen 80;
server_name www.zhubiaook.com;
root /app/web1;
index index.html index.htm;
}
server {
listen 80;
server_name blog.zhubiaook.com;
root /app/web2;
index index.html index.htm;
}

基于端口的虚拟主机

[11@root conf.d]# cat virtual.conf
# A virtual host using of port-based configuration
server {
listen 80 default_server;
root /app/web1;
index index.html index.htm;
}
server {
listen 8080;
root /app/web2;
index index.html index.htm;
}

基于IP的虚拟主机

[11@root conf.d]# cat virtual.conf
# A virtual host using of IP-based configuration
server {
listen 172.18.17.11:80;
root /app/web1;
index index.html index.htm;
}
server {
listen 192.168.17.11:80;
root /app/web2;
index index.html index.htm;
}
  1. 是否启用sendfile功能
Syntax: sendfile on | off;
Default: sendfile off;
Context: http, server, location, if in location

传统数据拷贝方法

Alt text
使用sendfile功能的数据拷贝方法

Alt text

参考文献:通过零拷贝实现有效数据传输

  1. 在长连接keep-alive模式下是否启用延迟发送。延迟发送指合并用户的多个请求后再一起发送
Syntax: tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location
  1. 设定相应报文首部Server字段的值
Syntax: server_tokens on | off | build | string;
Default: server_tokens on;
Context: http, server, location
---
on #Server: nginx/1.12.1
off #Server: nginx
build #可以在编译安装时加入选项 --build=NAME,将会在版本中加入添加的名字
e.g
--build=zhubiao
Server: nginx/1.12.1 (zhubiao)
# 我们也可以修改源码,来修改显示的服务器名
修改源码文件 nginx-1.12.1/src/core/nginx.h 下面的内容:
#define NGINX_VER "Zegine/" NGINX_VERSION
编译安装后的名字:Server: Zegine/1.12.1
  1. location 的配置,在一个server中可以配置多个location,用于实现从uri到文件系统路径的映射,用户请求时会从多个location中找到到一个最佳匹配的,而后应用该location中的配置。
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
---
# 以下排序按优先级高低从上到下排序:
= : 对uri做精确匹配,即相同才匹配
^~ : 对uri左侧做正则匹配
~ : 对uri做正则匹配
~* : 对uri做正则匹配,不区分大小写
不带符号 : 匹配左侧字符串
# example
location = /f1 {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
The “/f1” request will match configuration A,
the “/index.html” request will match configuration B,
the “/documents/document.html” request will match configuration C,
the “/images/1.gif” request will match configuration D,
the “/documents/1.jpg” request will match configuration E.
  1. 定义路径别名,注意location中alias和root的区别,root定义了站点的根目录,文件系统上的路径为root路径和uri路径的组合,而alias定义的路径就是文件系统的路径。
Syntax: alias path;
Default: —
Context: location
# example
location /image/ {
alias /app/web1/picture/;
}
  1. 定义缺省主页
Syntax: index file ...;
Default: index index.html;
Context: http, server, location
# exapmple
index index.$geo.html index.0.html /index.html;
  1. 定义错误页,并以指定的相应状态码进行响应
Syntax: error_page code ... [=[response]] uri;
Default: —
Context: http, server, location, if in location
# example
error_page 501 502 503 503 =200 /50x.html
location = /50x.html {
root /app/web/error;
}
  1. 按从左到右的顺序查找文件,查找到后就返回结果
Syntax: try_files file ... uri;
try_files file ... =code;
Default: —
Context: server, location
# example
location / {
root /app/web1;
try_files $uri $uri/index.html $uri/index.php;
}
location /images/ {
root /app/web1;
try_files $uri /picture/index.jpg1 =404;
}
  1. 输出nginx的基本状态信息
Syntax: stub_status;
Default:
Context: server, location
---
# 显示的信息
Active connections: 1
server accepts handled requests
15 15 16
Reading: 0 Writing: 1 Waiting: 0
# example
location /status {
stub_status;
}


七、客户端请求相关配置

  1. 设定那种浏览器不使用长连接
Syntax: keepalive_disable none | browser ...;
Default: keepalive_disable msie6;
Context: http, server, location
  1. 设定长连接的保持时间
Syntax: keepalive_timeout timeout [header_timeout];
Default: keepalive_timeout 75s;
Context: http, server, location
---
timeout #保持长连接的时间
[header_timeout] #设定相应头部显示的长连接时间 Keep-Alive:timeout=TIME
  1. 一次长连接中允许的最大请求数量
Syntax: keepalive_requests number;
Default: keepalive_requests 100;
Context: http, server, location
  1. 向客户端发送响应报文的超时时长,此处的时间指两次写操作的时间间隔,而不是整个传输时间,如果在该时间内,客户端没有收到报文,连接将关闭。
Syntax: send_timeout time;
Default: send_timeout 60s;
Context: http, server, location
  1. 设定存储请求报文实体部分的临时路径,路径子目录结构和数量
Syntax: client_body_temp_path path [level1 [level2 [level3]]];
Default: client_body_temp_path client_body_temp;
Context: http, server, location
---
level1 #指定一级子目录由几个16进制数组成
level2 #指定二级子目录由几个16进制数组成
# example
client_body_temp_path /app/nginx/client_temp 1 2
  1. 指定接收客户端请求报文实体部分内存缓存区的大小,超此部分将被存储在磁盘上(存储路径由 client_body_temp_path 设定)
Syntax: client_body_buffer_size size;
Default: client_body_buffer_size 8k|16k;
Context: http, server, location
# example
client_body_buffer_size 8k;


八、对客户端进行限制的相关配置

  1. 限制响应客户端的传输速率
Syntax: limit_rate rate;
Default: limit_rate 0;
Context: http, server, location, if in location
  1. 限制客户端使用除了指定的请求方法之外的其它方法
Syntax: limit_except method ... { ... }
Default: —
Context: location
---
method #GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH
# example
# 除了192.168.1.0/24网段可以使用任何请求方法,其它网段的只能使用GET请求方法
limit_except GET {
allow 192.168.1.0/24;
deny all;
}


九、文件操作优化配置

  1. 是否启用异步文件写磁盘功能
Syntax: aio on | off | threads[=pool];
Default: aio off;
Context: http, server, location
  1. 设定当文件大小超过多大时,直接写磁盘
Syntax: directio size | off;
Default: directio off;
Context: http, server, location
  1. 设定nginx缓存大小
Syntax: open_file_cache off;
open_file_cache max=N [inactive=time];
Default: open_file_cache off;
Context: http, server, location
  1. 是否缓存查找时发生错误的文件
Syntax: open_file_cache_errors on | off;
Default: open_file_cache_errors off;
Context: http, server, location
  1. 设定指定时间段内最少被使用多少次才能转为活动项
Syntax: open_file_cache_min_uses number;
Default: open_file_cache_min_uses 1;
Context: http, server, location
  1. 缓存检查频率
Syntax: open_file_cache_valid time;
Default: open_file_cache_valid 60s;
Context: http, server, location


十、访问控制

基于IP的访问控制

  1. 允许指定的网段或主机访问
Syntax: allow address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
  1. 禁止指定的网段或主机访问
Syntax: deny address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
  1. 实例:
    检查顺序为从上到下,一旦匹配将执行匹配行的访问控制,不再往下检查。
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}

基于用户名和密码的访问控制

  1. 使用基于basic机制的用户认证方式
Syntax: auth_basic string | off;
Default: auth_basic off;
Context: http, server, location, limit_except
  1. 指定验证用户名和密码的文件路径
Syntax: auth_basic_user_file file;
Default:
Context: http, server, location, limit_except
  1. 实例
# 1. 安装创建加密用户名和密码的工具httpd-tools
yum -y install httpd-tools
# 2. 创建用户
[11@root conf.d]# htpasswd -c /etc/nginx/conf.d/nginx_user zhubiao
New password:
Re-type new password:
Adding password for user zhubiao
# 3. 修改配置文件
location = / {
auth_basic "www.zhubiaook.com";
auth_basic_user_file /etc/nginx/conf.d/nginx_user;
root /app/web1;
index index.html;
}

Alt text


十一、定义日志

  1. 日志格式
Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http
# example
log_format delog '$remote_addr - $remote_user [$time_local] "$request" ';
  1. 访问日志
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
# example
access_log /var/log/nginx/access.log delog;
  1. 缓存日志的元数据
Syntax: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
Default: open_log_file_cache off;
Context: http, server, location
---
max=N #文件元数据的缓存数量,超过此值将使用LRU算法删除最少使用的
[inactive=time] #设定时长,在此时间内为未被使用将删除被缓存的文件元数据
[min_uses=N] #在inactive指定的时间内最少被使用多少次才激活为活动项
[valid=time] #检查的时间间隔
# example
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;


十二、gzip相关的配置

  1. 启用或禁用gzip压缩功能
Syntax: gzip on | off;
Default: gzip off;
Context: http, server, location, if in location
  1. 设定gzip压缩比,设定的值范围 [1,9]
Syntax: gzip_comp_level level;
Default:
gzip_comp_level 1;
Context: http, server, location
  1. 对某些客户端浏览器不执行压缩,通过匹配请求报文头部字段”User-Agent”值来判断。
Syntax: gzip_disable regex ...;
Default:
Context: http, server, location
  1. 设定启用压缩功能的报文最小长度值,以响应头部”Content-Length”中的值作报文的长度值。
Syntax: gzip_min_length length;
Default: gzip_min_length 20;
Context: http, server, location
  1. 设定启用压缩功能的HTTP协议的最小版本。
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http, server, location
  1. 设定启用压缩功能时,用于对响应报文做压缩的缓冲区的数量及每个缓冲区的大小
Syntax: gzip_buffers number size;
Default: gzip_buffers 32 4k|16 8k;
Context: http, server, location
  1. 指定对哪些MIME类型的资源才启用压缩
Syntax: gzip_types mime-type ...;
Default: gzip_types text/html;
Context: http, server, location
  1. 是否在响应头部插入字段“Vary: Accept-Encoding”
Syntax: gzip_vary on | off;
Default: gzip_vary off;
Context: http, server, location
  1. 对代理服务器请求的响应报文,在何种条件下启用压缩功能
Syntax: gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
Default: gzip_proxied off;
Context: http, server, location
  1. gzip压缩实例
[11@root conf.d]# ll /app/web/messages.txt
-rw-r--r-- 1 root root 1348498 Aug 21 03:07 /app/web/messages.txt
[11@root conf.d]# cat /etc/nginx/conf.d/zhubiao.conf
server {
listen 80 default_server;
root /app/web;
location / {
# Compresses responses using the "gzip"
gzip on;
gzip_comp_level 9;
gzip_min_length 1024;
gzip_http_version 1.0;
gzip_buffers 16 8k;
gzip_proxied any;
gzip_types text/xml text/plain;
gzip_vary on;
}
}
[11@root conf.d]# nginx -s reload

Alt text


十三、ssl相关的配置

  1. 对当前虚拟主机是否使用HTTPS协议
Syntax: ssl on | off;
Default: ssl off;
Context: http, server
  1. 当前虚拟主机证书文件路径
Syntax: ssl_certificate file;
Default:
Context: http, server
  1. 当前虚拟主机私钥文件(与证书配套的私钥)
Syntax: ssl_certificate_key file;
Default:
Context: http, server
  1. 支持的ssl协议版本
Syntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2] [TLSv1.3];
Default: ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
Context: http, server
  1. 定义SSL会话参数缓存的类型和大小
Syntax: ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
Default: ssl_session_cache none;
Context: http, server
---
off #不使用缓存,并明确告知客户端缓存不可使用
none #告诉客户端缓存可用,实际服务器没有缓存
[builtin[:size]] #OpenSSl内建缓存,为每个worker进程独有,如果大小不指定,默认为20k,使用OpenSSl内建缓存会导致内存碎片
[shared:name:size] #所有worker进程共享一个缓存,1M的内存可以存储4000个会话。
  1. 设定多长时间内客户端可重复使用缓存的会话参数
Syntax: ssl_session_timeout time;
Default: ssl_session_timeout 5m;
Context: http, server
  1. SSL配置实例
    本实例创建两个使用HTTPS协议的虚拟主机
    a. 创建站点www.zhubiaook.com的私钥和证书文件
[11@root conf.d]# cd /etc/pki/tls/certs/
[11@root certs]# make zhubiaook.crt
...
Enter pass phrase:
Verifying - Enter pass phrase:
...
Enter pass phrase for zhubiaook.com.key:
...
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:yunnan
Locality Name (eg, city) [Default City]:xuanwei
Organization Name (eg, company) [Default Company Ltd]:zhubiaook.com
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:www.zhubiaook.com
Email Address []:

b. 创建站点www.moretz.com的私钥和证书文件

[11@root certs]# make moretz.crt
...
Verifying - Enter pass phrase:
...
Enter pass phrase for moretz.key:
...
Country Name (2 letter code) [XX]:US
State or Province Name (full name) []:georgia
Locality Name (eg, city) [Default City]:Atlanta
Organization Name (eg, company) [Default Company Ltd]:moretz.com
Organizational Unit Name (eg, section) []:performer
Common Name (eg, your name or your server's hostname) []:www.moretz.com
Email Address []:

c. 复制证书文件到/etc/nginx/conf.d/ssl目录下,并去除私钥加密密码

[11@root certs]# mkdir /etc/nginx/conf.d/ssl
[11@root certs]# cp zhubiaook* moretz* /etc/nginx/conf.d/ssl/
[11@root certs]# cd /etc/nginx/conf.d/ssl/
[11@root ssl]# openssl rsa -in zhubiaook.key -out zhubiaook.key
Enter pass phrase for zhubiaook.com.key:
writing RSA key
[11@root ssl]# openssl rsa -in moretz.key -out moretz.key
Enter pass phrase for moretz.key:
writing RSA key
[11@root ssl]# mv zhubiaook.com.crt zhubiaook.crt
[11@root ssl]# ls
moretz.crt moretz.key zhubiaook.com.key zhubiaook.crt zhubiaook.key

d. 创建配置文件

[11@root conf.d]# cat /etc/nginx/conf.d/ssl.conf
server {
listen 443 ssl;
server_name www.zhubiaook.com;
root /app/web1;
ssl on;
ssl_certificate /etc/nginx/conf.d/ssl/zhubiaook.crt;
ssl_certificate_key /etc/nginx/conf.d/ssl/zhubiaook.key;
ssl_session_cache shared:SSLZ:1m;
ssl_session_timeout 10m;
}
server {
listen 443 ssl;
server_name www.moretz.com;
root /app/web2;
ssl on;
ssl_certificate /etc/nginx/conf.d/ssl/moretz.crt;
ssl_certificate_key /etc/nginx/conf.d/ssl/moretz.key;
ssl_session_cache shared:SSLM:1m;
ssl_session_timeout 10m;
}

e. 导入证书

Alt text


十四、URI重定向

  1. 使用正则表达式匹配用户请求的URI,对匹配到的重定向
Syntax: rewrite regex replacement [flag];
Default:
Context: server, location, if
---
flag:
last #在本条匹配的rewrite规则执行完后,对所其所在的标签再次发起请求;
break #在本条匹配的rewrite规则执行完后,终止匹配;
redirect #返回302临时重定向给客户端,客户端再次通过返回的地址发起请求
permanent #返回301永久定向给客户端,客户端再次通过返回的地址发起请求
# example
server {
listen 80 default_server;
root /app/web;
location / {
rewrite ^/(.*)$ /images/$1 break;
}
}
server {
listen 80 default_server;
root /app/web;
rewrite ^/(.*)$ https://www.moretz.com/$1 redirect;
}
  1. return
Syntax: return code [text];
return code URL;
return URL;
Default: —
Context: server, location, if
# example
location / {
return 301 https://www.zhubiaook.com;
}
server {
listen 80 default_server;
root /app/web;
location / {
return 404;
}
error_page 404 /404.html;
location = /404.html {
root /app/web/error;
  1. 是否对模块ngx_http_rewrite_module启用日志记录功能,并将其记录到error_log中。
Syntax: rewrite_log on | off;
Default: rewrite_log off;
Context: http, server, location, if
  1. 自定义变量,变量的值可以是文本,另一个变量或表达式。
Syntax: set $variable value;
Default: —
Context: server, location, if
  1. if (conditon) {…}
Syntax: if (condition) { ... }
Default:
Context: server, location
---
condition:
比较操作符
==, != #比较字符串是否相同
~, !~ #是否匹配字符串(使用正则表达式),区分大小写
~*, !~* #是否匹配字符串(使用正则表达式),不区分大小写
文件存在性判断
-e, !-e #判断文件(普通文件,目录,符号链接...)是否存在
-f, !-f #判断普通文件是否存在
-d, !-d #判断目录是否存在
-x, !-x #判断文件是否可执行


十五、防盗链

  1. 指定对请求报文头部中的 “Referer” 字段做何种检查,检查结果将决定变量$invalid_referer的值是空,还是1
Syntax: valid_referers none | blocked | server_names | string ...;
Default:
Context: server, location
---
none #请求报文头部中没有Referer字段
blocked #请求报文头部有Referer字段,但没有值,比如被反代理服务器删除。
server_names #请求报文头部有Referer字段,并且包含本主机的主机名
string #匹配请求报文头部Referer字段的值
  1. 实例
[11@root conf.d]# cat zhubiao.conf
server {
listen 80 default_server;
root /app/web1;
server_name www.zhubiaook.com;
}
server {
listen 80;
root /app/web2;
server_name www.moretz.com;
valid_referers none block server_names ~\.baidu\.;
if ($invalid_referer){
return 404;
}
error_page 404 /404.html;
location = /404.html {
alias /app/web2/404.html;
}
}

Alt text


十五、反向代理

反向代理模块Module ngx_http_proxy_module可以将用户的请求转移到后端的服务器上。

  1. 反向代理将用户的请求调度到后端服务器,指定后端服务器的URL
Syntax: proxy_pass URL;
Default: —
Context: location, if in location, limit_except
---
# example
# 对匹配到的uri掉度到 http://host[:port]/uri
location /uri/ {
proxy_pass http://host[:port]
}
# 对匹配到的uri掉度到 http://host[:port]
location /uri/ {
proxy_pass http://host[:port]/
}
  1. 反向代理服务器上将请求报文发给后端服务器之前添加自定义首部
Syntax: proxy_set_header field value;
Default: proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
Context: http, server, location
# example
proxy_set_header Real_IP $remote_addr;
proxy_set_header Forward_For $proxy_add_x_forwarded_for;
  1. 定义用于proxy的缓存的文件系统路径和缓存参数
Syntax: proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size];
Default:
Context: http
---
path #缓存路径
levels #缓存在磁盘上存储的目录层次和数量
keys_zone #缓存区域名称和大小
inactive #非活动时间
max_size #proxy缓存大小
# example
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;
  1. 指明调用 proxy_cache_path 所定义的缓存区
Syntax: proxy_cache zone | off;
Default: proxy_cache off;
Context: http, server, location
---
zone # proxy_cache_path 参数keys_zone=name:size所定义的区域名称
  1. 指明proxy缓存中的键
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
  1. 反向代理中定义对不同响应状态码内容的缓存时间
Syntax: proxy_cache_valid [code ...] time;
Default:
Context: http, server, location
  1. 定义当被代理的后端服务出现何种故障,直接使用过期的缓存响应客户端
Syntax: proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | http_429 | off ...;
Default: proxy_cache_use_stale off;
Context: http, server, location
  1. 定义对客户端使用何种请求方法才缓存
Syntax: proxy_cache_methods GET | HEAD | POST ...;
Default: proxy_cache_methods GET HEAD;
Context: http, server, location
  1. 响应客户端请求时,反向代理服务器隐藏哪些后端响应头部字段。默认设置中,反向代理服务器不向客户端发送后端服务器的 “Date”, “Server”, “X-Pad”, and “X-Accel-…” 头部信息。
Syntax: proxy_hide_header field;
Default:
Context: http, server, location
  1. 反向代理服务器与后端服务器连接超时时间
Syntax: proxy_connect_timeout time;
Default: proxy_connect_timeout 60s;
Context: http, server, location
  1. 反向代理服务器发送请求给后端服务器的超时时间
Syntax: proxy_send_timeout time;
Default: proxy_send_timeout 60s;
Context: http, server, location
  1. 反向代理服务器接收后端响应的超时时间
Syntax: proxy_read_timeout time;
Default: proxy_read_timeout 60s;
Context: http, server, location


十六、自定义首部

模块ngx_http_headers_module 用于给客户端发送的响应报文头部中添加自定义的头部字段。

  1. 添加自定义首部
Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location
  1. ?
Syntax: add_trailer name value [always];
Default: —
Context: http, server, location, if in location


十七、FastCGI

模块ngx_http_fastcgi_module 实现将请求转发给后端FastCGI服务器,比如PHP-FPM服务器。

  1. 指定转发的后端服务器,后端服务器地址可以为域名,或IP和端口
Syntax: fastcgi_pass address;
Default: —
Context: location, if in location
# exapmple
fastcgi_pass localhost:9000;
  1. FastCGI默认的主页
Syntax: fastcgi_index name;
Default: —
Context: http, server, location
# example
fastcgi_index index.php;
  1. 设置传递给FastCGI服务器的参数值,值可以是变量,字符串。
Syntax: fastcgi_param parameter value [if_not_empty];
Default: —
Context: http, server, location
# example
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
  1. 定义FastCGI缓存文件系统路径及参数
Syntax: fastcgi_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size];
Default: —
Context: http
  1. 指明调用 fastcgi_cache_path 所定义的缓存区
Syntax: fastcgi_cache zone | off;
Default: fastcgi_cache off;
Context: http, server, location
  1. 指明FastCGI缓存中的键
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
  1. 对哪些请求方法使用缓存
Syntax: fastcgi_cache_methods GET | HEAD | POST ...;
Default: fastcgi_cache_methods GET HEAD;
Context: http, server, location
  1. 对响应的内容,被客户端请求多少次后才缓存
Syntax: fastcgi_cache_min_uses number;
Default: fastcgi_cache_min_uses 1;
Context: http, server, location
  1. 默认情况下,后端的FastCGI服务器再发送了响应报文后将关闭与nginx服务器之间的连接,但是,当fastcgi_keep_conn设置为on时,nginx服务器将通知FastCGI服务器保持连接,对于长连接,这种设置很有必要。
Syntax: fastcgi_keep_conn on | off;
Default: fastcgi_keep_conn off;
Context: http, server, location

10 .针对于不同响应状态码设置不同的缓存时间

Syntax: fastcgi_cache_valid [code ...] time;
Default: —
Context: http, server, location
# example
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;


十八、负载均衡

模块 ngx_http_upstream_module 用于将多台后端服务器组合成一个服务器组,这个服务器组可以被 proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass 和 memcached_pass 命令调用,从而达到组中的服务器共同承担负载的功能,实现负载均衡。

  1. 定义后端服务器组
Syntax: upstream name { ... }
Default: —
Context: http
# example
upstream backend {
server backend1.example.com weight=5;
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server backup1.example.com backup;
}
  1. 组中后端服务器的地址、权重等参数
Syntax: server address [parameters];
Default:
Context: upstream
---
[parameters]
weight=number #权重
max_conns=number #最大并发连接数
max_fails=number #连接失败的尝试次数,超出后将标记为不可用
fail_timeout=time #连接失败的超时时间,超出后将标记为不可用
backup #标记为备用,其它服务器全部宕机后才启用
down #标记为不可用
  1. 为每个worker进程保留的最大空闲长连接数量
Syntax: keepalive connections;
Default:
Context: upstream

调度算法

  1. 基于源地址的hash调度算法
Syntax: ip_hash;
Default:
Context: upstream
  1. 最少连接调度算法
Syntax: least_conn;
Default:
Context: upstream
  1. 基于指定的key的hash表来实现调度
Syntax: hash key [consistent];
Default:
Context: upstream


十九、实现传输层TCP/UDP的反向代理或负载均衡

  1. 定义stream段相关的业务,与http配置段同级
Syntax: stream { ... }
Default:
Context: main
  1. 配置实例
    使用nginx作TCP/UPD的反向代理,实现后端MySQL服务器的负载均衡

Alt text
配置文件

[20@root nginx]# vim /etc/nginx/nginx.conf
...
stream {
upstream mysqlservers {
server 172.18.17.10:3306;
server 172.18.17.21:3306;
}
server {
listen 172.18.17.20:3306;
proxy_pass mysqlservers;
proxy_timeout 60s;
proxy_connect_timeout 10s;
}
}

测试

Alt text


本节完,后面的博客将以一个综合性的实验来演示上面的配置,请看后文。