nginx总结

nginx安装和基本讲解(centos7)

nginx安装

  1. 打开http://nginx.org/en/download.html Mainline version是开发版本,Stable version是稳定版本,Legacy versions是历史版本
  2. 打开最下方的stable and mainline可以看centos的安装教程
  3. sudo yum install yum-utils
  4. 创建/etc/yum.repos.d/nginx.repo写入以下内容
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx.org/packages/centos/7/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://nginx.org/keys/nginx_signing.key

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

上面是稳定版本,下面是开发版本

  1. 如果想安装开发版本执行
    sudo yum-config-manager –enable nginx-mainline
  2. 安装命令
    sudo yum install nginx
  3. 使用nginx-v验证安装成功

基本参数的使用

nginx安装目录

  • 使用npm -ql nginx可以看已经安装服务在操作系统上的文件和目录
路径 类型 作用
/etc/logrotate.d/nginx 配置文件 Nginx日志轮转,用于logrotate服务的日志切割和清理
/etc/nginx
/etc/nginx/nginx.conf
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
目录、配置文件 nginx主配置文件
nginx.conf是主要配置
在没有做变更的情况下会读default.conf,默认加载的配置文件
/etc/nginx/fastcgi_params
/etc/nginx/uwsgi_params
/etc/nginx/scgi_params
配置文件 cgi配置相关,fastcgi配置
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/win-utf
配置文件 编码转换映射转化文件
/etc/nginx/mime.types 配置文件 设置http协议的Content-Type与扩展名对应关系
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
配置文件 用于配置出系统守护进程管理器管理方式
/usr/lib64/nginx/modules
/etc/nginx/modules
目录 nginx模块目录
/usr/sbin/nginx
/usr/sbin/nginx-debug
命令 nginx服务的启动管理的终端命令
/usr/share/doc/nginx-x.xx.x
/usr/share/doc/nginx-x.xx.x/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
文件、目录 nginx的手册和帮助文件
/var/cache/nginx 目录 nginx的缓存目录
/var/log/nginx 目录 nginx的日志目录

nginx安装编译参数

  • 使用nginx -V可查看安装编译参数
编译选项 作用
–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
执行对应模块时nginx所保留的临时性文件
–user=nginx
–group=nginx
设定nginx进程启动的用户和组用户
–with-cc-opt=’parameters’ 设置额外的参数将被添加到CFLAGS变量
–with-ld-opt=’parameters’ 设置附加的参数,链接系统库

默认配置语法

  • 打开/etc/nginx/nginx.conf文件可以配置nginx,
    文件中最下面一行
    1
    include /etc/nginx/conf.d/*.conf;

表示包含了这个目录下的所有conf文件,打开了只有一个default.conf

  • nginx.conf包含一下配置
  1. 基本配置
    user:设置nginx服务的系统使用用户,和上面编译参数中–user对应
    worker_processes:工作进程数,跟nginx多进程有关系,增大并发处理,一般和cpu核心数保持一致
    error_log:nginx的错误日志路径
    pid:nginx服务启动时候pid

  2. events模块表示nginx使用epoll内存模型的参数
    worker_connections:每个进程成允许最大连接数,可以是最大65535,一般一万左右
    use:工作进程数,使用哪种内核模型,linux是select epoll

  3. http大括号中表示http协议的一些配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    http{
    #子配置文件
    include /etc/nginx/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 /var/log/nginx/access.log main;
    #nginx一大优势,默认打开
    sendfile on;
    #tcp_nopush on;

    #超时时间
    keepalive_timeout 65;
    server {
    # 监听端口,服务名
    listen 80;
    server_name localhost; #自己主机名或域名
    #location控制每一层路径访问
    #表示每个目录下默认访问index.html或者index.htm
    #如果访问根/,那么去/usr/share/nginx/html文件夹下找index.html和index.htm
    location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    }
    #错误码,在500,502,503,504时候都访问/50x.html
    error_page 500 502 503 504 /50x.html;
    #访问/50x.html存放在这个目录下
    location = /50x.html {
    root /usr/share/nginx/html;
    }
    }
    server{
    ... ...
    }
    }
  • 一个http有多个server,一个server有多个location

nginx配置

日志配置

  • error.log nginx处理http请求的错误状态,以及本身运行服务的状态
  • access_log nginx每一次http请求的访问状态

log_format配置

log_format将产生的变量组织到一次,写入access_log中

语法:Syntax: log_format name [escape=defalt|json]
log_format:配置关键字,name表示格式名字,后面是所有的字符串变量

默认配置:log_format combined “…”
Context:http表示只能配置到http的模块下面

access_log

1
2
3
4
5
6
7
8
....
#日志类型
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;
....
  • 上述代码定义了一个名叫main的日志类型,然后在access_log中声明了地址和使用main日志类型
  • 小技巧:配置完了可以运行 nginx -tc /etc/nginx/nginx.conf检查配置语法是否正确

log变量

  1. http请求变量
    arg_PARAMETER:请求头中的参数
    http_HEADER:请求头,如$http_user_agent
    sent_http_HEADER:返回的头部(response的header)

    都要小写,横杠换成下划线
  2. 内置变量
    内置变量比较多,打开官方文档查看 http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

  3. 自定义变量
    //TODO

nginx模块

官方模块

–with-http_stub_status_module

  • Nginx的客户端状态,用于监控nginx当前的一些信息
    配置语法:stub_status,打开此功能
    默认没配置
    需要配置在server或者location中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    http{
    ...
    server{
    ...
    location /mystatus {
    stub_status;
    }
    }
    }
  • 此时访问url/mystatus会闲事当前nginx客户端状态

    Active connections: 1
    server accepts handled requests
    5 5 5
    Reading: 0 Writing: 1 Waiting: 0

Active connections表示nginx当前活跃的连接数
server accepts handled requests下面的三个数
第一个数表示nginx处理接受握手总次数
第二个数表示nginx处理的连接数
第三个表示nginx表示总得请求书
正常是第一第二要相等表示没有丢失

Reading: 0 Writing: 1 Waiting: 0
表示正在读、正在写、正在等待(没读没写有链接)的个数

–with-http_random_index_module

  • 目录中选择一个随机主页

语法:random_index on|off;
默认:random_index off;
限制:location

1
2
3
4
5
location / {
root /usr/share/nginx/html;
random_index on;
#index index.html index.htm;
}
  • 此时访问/,会将/usr/share/nginx/html目录下的文件随机返回一个
  • 注意此模块不会选择隐藏的文件作为随机主页

–with-http-sub-module

  • 用于http内容替换
sub_filter
  • 指定字符串的替换

语法:sub_filter string replacement;
默认:无
限制:http,server,location

1
2
3
4
5
6
7
8
9
http{
server{
location / {
root /usr/share/nginx/html;
index index.html index.htm;
sub_filter 'Welcome' 'www';
}
}
}

  • 会将返回的第一个Welcome替换成www
sub_filter_last_modified
  • 用于服务端和客户端进行请求校验服务端内容是否发生改变,判断是否有更新,用于缓存
    语法:sub_filter_last_modified no|off
    默认:sub_filter_last_modified off;
    限制:http,server,location
sub_filter_once on|off
  • 匹配第一个还是所有的
    语法:sub_filter_once on|off
    默认:sub_filter_once on
    限制:http,server,location

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    http{
    server{
    location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    sub_filter 'Welcome' 'www';
    sub_filter_once off;
    }
    }
    }
  • 会将返回结果的所有Welcome替换成www

第三方模块

nginx的请求限制

连接频率的限制

  • http请求建立在一次TCP连接基础之上
  • 一次TCP连接至少产生一次HTTP请求

limit_conn_zone

  • 存储链接状态的空间zone
    语法:limit_conn_zone key zone=name:size
    默认:无
    限制:http

key:以什么作为限制对象的名字,比如以ip地址为限制变量,那么就写$binary_remote_addr为key
zone:name表示实现限制的时候调用的空间名字,size是这个空间的大小,1M共享空间可以保存3.2万个32位的状态,1.6万个64位的状态。
如果共享内存空间被耗尽,服务器将会对后续所有的请求返回 503 (Service Temporarily Unavailable) 错误。

limit_conn

  • 配置请求限制
    语法:limit_conn zone number;
    默认:无
    限制:http,server,location

zone:上面存储空间的名字,和上面的zone对应
number:并发限制的个数

这个无论如何我也实现不了效果 //TODO

请求频率的限制

limit_req_zone

  • 存储的空间zone
    语法:limit_req_zone key zone=name:size rate=rate
    默认:无
    限制:http

key:以什么作为限制对象的名字,比如以ip地址为限制变量,那么就写$binary_remote_addr为key
zone:name表示实现限制的时候调用的空间名字,size是这个空间的大小
rate:请求的速率,秒为单位

limit_req

语法:limit_req zone=name [burst=number] [nodelay];
默认:无
限制:http,server,location
zone:调用的空间名字

其中burst和nodelay参考这篇博客

nginx访问控制

基于ip的访问控制

http_access_module

语法:allow address|CIDR|unix:|all
默认:无
限制:http,server,location,limit_except

语法:deny address|CIDR|unix:|all
默认:无
限制:http,server,location,limit_except

1
2
3
4
5
6
7
http{
deny 10.6.5.99;
allow all;
server{
...
}
}
  • 此时只有10.6.5.99是不能访问返回403,其他都能访问
  • 注意,如果allow all在上面,此时都能访问,deny将不起作用
  • 也可以使用ip段的方式,如192.168.0.0/24

http_x_forwarded_for

  • 直接用remote_addr只能看到最后一个ip
  • x_forward_for可以获取到一路上获取的所有ip
  • 是协议要求,但是不一定都有,也是可以被修改的

基于用户的信任登陆

http_auth_basic_module

语法:auth_basic string|off;
默认:auth_basic off;
限制:http,server,location,limit_except;

语法:auth_basic_user_file file;
默认:无
限制:http,server,location,limit_except

1
2
3
4
5
6
7
8
9
10
http {
...
server {
...
location / {
root html;
auth_basic "请输入你的用户名和密码";
auth_basic_user_file antu_conf;
index index.html index.htm;
}
  • 此时会提示输入用户名和密码,并且用户名和密码在antu_conf文件中对应(位置相对于conf),密码文件格式参考 官方文档,可以使用htpasswd生成

静态资源web服务

文件读取配置

sendfile on|off

  • 文件读取
    语法:sendfile on|off
    默认:sendfile off
    限制:http,server,location,if in location

tcp_nopush

  • sendfile开启的情况下,提高网络报的传输效率
    语法:tcp_nopush on|off;
    默认:tcp_nopush off;
    限制:http,server,location
  • 原理相当于十个快递叫十个快递员优化成十个快递一次性叫一个,大文件适用

tcp_nodelay

  • keepalive连接下,提高网络传输的实时性
    语法:tcp_nodelay on|off;
    默认:tcp_nodelay on;
    限制:http,server,location;
  • 报文不要等待,直接发送

文件压缩

gzip

  • 压缩传输
    语法:gzip on|off;
    默认:gzip off;
    限制:http,server,location,if in location
  • 原理是nginx端压缩,然后浏览器端解压缩,通用协议的压缩

gzip_comp_level

  • 压缩比率
    语法:gzip_comp_level leve;
    默认:gzip_comp_level 1;
    限制:http,server,location
  • 数字越大压缩比率越大,结果越小,但是会影响服务器性能

gzip_http_version

  • gzip的http协议版本
    语法:gzip_http_version 1.0|1.1
    默认:gzip_http_version 1.1
    限制:http,server,location

http_gzip_static_module

  • 预读gzip功能,先找gzip文件,如果有直接发送这个,节省压缩的时间
  • 预读的gz是事先自己压缩好的

http_gunzip_module

  • 很少浏览器不支持gzip,需要用这个来压缩

浏览器缓存

校验是否过期

  • Expires:http1.0的缓存协议,CacheControl(max-age):http:1.1的协议
  • 定义了缓存的有效期
  • 客户端先去检查是否在有效期内
  • 如果超期了会调用etag和last-modified验证

超期验证

last-modified后跟了一个时间,用来跟服务器端本地文件校验,如果服务端的时间和last-modified时间不一致,那么返回新文件

  • last-modified传输的是时间,精确到秒,如果是一秒内的改动就会出现问题
  • etag是以一串特殊的字符串来进行校验
  • 常用的是etag来进行校验

图片丢失

  • 如果命中缓存则状态码是304

nginx的过期设置

expires

  • 添加Cache-Control,Expires头,设置过期时间
    语法:expires [modified] time;expires epoch|max|off;
    默认:expires off;
    限制:http,server,location,if in location

nginx跨域访问

add_header

语法:add_header name value [always]
默认:无
限制:http,server,location,if in location

实现跨站访问则要设置

1
Access-Control-Allow-Origin:允许跨域的域名,或者*允许所有跨域访问

防盗链

  • 防止网站资源被盗用

http_refer

语法:valid_referers none|blocked|server_names|string …
默认:无
限制:server,location

1
2
3
4
5
6
7
location ~ .*\.(jpg|gif|png)$ {
valid_referers none blocked 119.28.190.215;
if ($invalid_referer) {
return 403;
}
root /opt/app/code/images;
}
  • none : 允许没有http_refer的请求访问资源;
  • blocked : 允许不是http://开头的,不带协议的请求访问资源;
  • 119.28.190.215 : 只允许指定ip来的请求访问资源,可以用正则匹配;

  • 根据header存储的refer头进行验证,防止被别的域名套用

  • 防盗链有限,因为refer信息是可以伪造

代理

proxy_pass

  • 代理配置语法
    语法:proxy_pass URL;
    默认:无
    限制:location,if in location,limit_except

代理缓冲

  • 代理开启缓冲
    语法:proxy_buffering on|off;
    默认:proxy_buffering on
    限制:http,server,location
    扩展:proxy_buffer_size,proxy_buffers,proxy_busy_buffers_size

proxy_redirect

  • 跳转重定向
    语法:proxy_redirect default|off|redirect replacement
    默认:proxy_redirect default;
    限制:http,server,location
  • 当请求是301重定向的时候启用此模块,重写重定向301的地址

proxy_set_header

  • 设置头信息
    语法:proxy_set_header field value;
    默认:proxy_set_header Host $proxy_host;proxy_set_header Connection close;
    限制:http,server,location
    扩展:proxy_hide_header隐藏头,proxy_set_body

proxy_connect_timeout

  • 代理超时
    语法:proxy_connect_timeout time;
    默认:proxy_connect_timeout 60s;
    限制:http,server,location

反向代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
location /{
proxy_pass http://127.0.0.1:8080; # 请求转向本虚拟机的8080端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; #获取真实ip
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#获取代理者的真实ip
proxy_redirect off;
}

请求此location会被请求到http://127.0.0.1:8080地址

正向代理

1
2
3
4
5
6
location{
if($http_x_forwarded_for !~* "^xxx\.xxx\.xxx\.xxx"){
return 403;
}
...
}

负载均衡

upstream

语法:upstream name{…}
默认:无
限制:http

1
2
3
4
5
6
7
8
9
10
11
12
13
http{
upstream hhh{
server 127.0.0.1:8080;
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}
server{
location /{
proxy_pass http://hhh;
//反向代理的配置
}
}
}

  • 此时访问会时候会轮询访问8080,8081,8082
  • 如果一个节点挂掉了会自动下线
参数 含义
down 当前server下线,不参与负载均衡
backup 预留的备份服务器,本身不提供服务,当同组其他节点都挂掉才会提供服务
max_fails 允许请求失败的次数
fail_tmeout 经过max_fails失败后,服务暂停的时间,默认是10秒,过了再次检查是否失败
max_conns 限制最大的接收的连接数