1、Nginx Web 入门简介

Nginx是一个高性能HTTP、反向代理、IMAP、POP3、SMTP服务器

Nginx特点:高性能、轻量级、占有内存少、并发能力强

 

Nginx相对于Apache优点如下:

  • 高并发相应性能非常好,官方nginx处理静态文件并发5w/s
  • 负载均衡及反向代理性能非常强
  • 系统内存和cpu占用率低
  • 可对后端服务进行健康检查
  • 支持PHP CGI 方式和 FastCGI 方式
  • 可以作为缓存服务器、邮件代理服务器
  • 配置代码简洁且容易上手

2、Nginx工作原理

nginx web 服务器主要是有各种模块协同工作,从结构上分为核心模块、基础模块、第三方模块

 核心模块:http模块、event模块和mail模块

 基础模块:http access模块、http fastcgi模块、http proxy模块和http rewrite模块

 第三方模块:http upstream request hash模块、notice模块和http access key 模块、limit_req模块等

从功能上分为三类:

 handlers(处理模块):直接处理请求,并进行输出内容和修改headers信息等操作,handlers处理器模块一般只有一个

files(过滤器模块):主要对其他处理器模块输出的内容进行修改操作,最后由nginx输出、

proxies(代理模块):是nginx的http upstream之类模块,这些模块主要与后端一些服务比如fastcgi等进行交互,实现服务代理和负载均衡

 

Nginx的高并发得益于采用的epoll模型

Apache采用的select模型

select模型的特点: 当用户发起一次请求,select模型会进行一次遍历扫描,因此效率低下

epoll模型的特点:当用户发起请求,epoll模型会直接进行处理,效率高,并无连接限制

3、nginx应用场景

   静态服务:浏览器缓存 ,防资源

       html|jpg|png......

  代理服务:

    正向代理:内访外

    反向代理:外访内,和负载均衡是一样,但是工作方式有区别

  负载均衡:

  安全服务:

    访问控制:

      基于IP的

      基于身份认证

    访问限制

    WAF

      云waf

      硬件waf

        DDOS攻击

        CC攻击

        SQL注入

        。。。

      nginx+lua

  架构

    LNMP

      Linux Nginx Mysql Php

    LNMT

       Linux Nginx Mysql Tomcat

 

4、Nginx安装

1)EPEL源

  版本低,功能少

2)官方源

  官方编译好,封装rpm包,并提供yum源,推荐

3)源代码

  自己下载源代码,使用configure/make/make install

  安装复杂费时,升级麻烦

1、配置nginx官方yum库,安装官方nginx

[root@localhost ]# vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

直接安装yum install nginx,安装最新的版本的nginx

yum --showduplicates list nginx | expand
查看源中有多少版本的nginx

 

 选择对应的版本进行安装

例如选择版本是1.6.0的,

[root@localhost yum.repos.d]# yum install nginx-1.16.0

 安装完成后,检验安装版本

[root@localhost yum.repos.d]# nginx -v
nginx version: nginx/1.16.0

 

2、[root@localhost yum.repos.d]# rpm -ql nginx

Nginx主配置文件

  /etc/nginx

  /etc/nginx/nginx.conf
  /etc/nginx/conf.d
  /etc/nginx/conf.d/default.conf

Cgi、Fastcgi、Uwcgi配置文件

  /etc/nginx/fastcgi_params

  /etc/nginx/scgi_params

  /etc/nginx/uwsgi_params

Nginx编码转换映射文件

  /etc/nginx/koi-utf

  /etc/nginx/win-utf
  /etc/nginx/koi-win

http协议的Content-Type与扩展名
  /etc/nginx/mime.types
配置系统守护进程管理器
  /usr/lib/systemd/system/nginx.service

Nginx日志轮询,日志切割

  /etc/logrotate.d/nginx

Nginx终端管理命令

  /usr/sbin/nginx
  /usr/sbin/nginx-debug

Nginx模块命令

  /etc/nginx/modules

  /usr/lib64/nginx
  /usr/lib64/nginx/modules

Nginx默认站点目录

  /usr/share/nginx
  /usr/share/nginx/html
  /usr/share/nginx/html/50x.html
  /usr/share/nginx/html/index.html

Nginx的帮助手册

  /usr/share/doc/nginx-1.16.0
  /usr/share/doc/nginx-1.16.0/COPYRIGHT
  /usr/share/man/man8/nginx.8.gz

 

Nginx的缓存目录

  /var/cache/nginx

Nginx的日志目录

  /var/log/nginx

3、官方源nginx带的编译选项

[root@localhost yum.repos.d]# nginx -V
nginx version: nginx/1.16.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --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             #临时缓存文件

            --user=nginx
            --group=nginx                                  #设置Nginx进程启动用户和组

            --with-compat
            --with-file-aio
            --with-threads
            --with-http_addition_module
            --with-http_auth_request_module
            --with-http_dav_module
            --with-http_flv_module
            --with-http_gunzip_module
            --with-http_gzip_static_module
            --with-http_mp4_module
            --with-http_random_index_module
            --with-http_realip_module
            --with-http_secure_link_module
            --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module
            --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC'     #设置额外的参数将被添加到CFLAGS变量
            --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'                                                                                #设置附加的参数,链接系统库

如果企业之前的Nginx都是通过源码安装,只需要通过nginx -V查看编译选项,部署新的服务器,获得版本号,configure选项

5、Nginx配置文件

Nginx主配置文件 /etc/nginx/nginx.conf 是一个纯文本类型的文件,整个配置文件是以区块的形式组织的,一般,每个区块以一对大括号{}来表示开始与结束。

  1、CoreModule 核心模块          全局模块

  2、EventModule 事件驱动模块

  3、HttpCoreModule http内核模块       局部模块

 

  需了解扩展项

  CoreModule层下可以有Event、http

  http模块层允许有多个Server层,Server主要用于配置多个网站

  Server层又允许有多个Location,Location主要用于定义网站访问路径#CoreModule核心模块:


user nginx;                      #Nginx进程所使用的用户
worker_processes
1;                 #Nginx运行的work进程数量(建议与cpu数量一致或auto) error_log /var/log/nginx/error.log warn;     #Nginx错误日志存放路径 pid /var/run/nginx.pid;           #Nginx服务运行后产生的pid进程号 #Event模块 events { worker_connections 1024;            #每个worker进程支持的最大连接数
  use  epool;                    #事件驱动模型,epool默认,
} #http内核模块
#公共的配置定义在http{} 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; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on;
  #使用server配置网站,每个server{}代表一个网站(简称虚拟主机)
  server {
    listen 80;              #监听端口,默认80
    server_name localhost;       #提供服务的域名或主机名
    access_log host.access.log;    #访问日志
    #控制网站访问路径
    location / {
      root /usr/share/nginx/html;  #存放网站代码路径
      index index.php index.html index.htm; #服务器返回的默认页面文件
    }
  #指定错误代码,统一定义错误页面,错误代码重定向到新的location
    error_page  500 502 503 504 /50x.html

}
   include /etc/nginx/conf.d/*.conf; }

 

6、Nginx配置网站

1、在/etc/nginx/conf.d/下新建配置文件,要求一定是.conf结尾,然后将默认文件关闭

[root@localhost ]# cd /etc/nginx/conf.d/
[root@localhost conf.d]# mv default.conf default.conf.bak
[root@localhost conf.d]# vim game.conf
server {
    listen 80;
    server_name game.com;
    
    location / {
        root /home/wwwroot/gms;
        index index.php;

    } 


}

配置完,进行语法测试

[root@localhost conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

2、获取网页代码

[root@localhost ~]# cd /home
[root@localhost home]# mkdir wwwroot/ -p

 将后台代码上传职wwwroot下

3、启动或重载nginx

systemctl restart nginx / systemctl reload nginx

4、通过域名访问,要修改windows的本地hosts文件

C:\Windows\System32\drivers\etc

gmsip 域名

 

有可能出现的错误:

1)解析问题

2)nginx无法启动

  端口是否被占用

  配置文件写错

3)重载失败

  配置文件写错了

      一定检测nginx -t

4)日志

 

 

6、Nginx目录索引

Nginx默认是不允许列出整个目录浏览下载

Syntax:   autoindex on | off;

Default:    autoindex off;

Context:   httpserverlocation

 

#autoindex常用参数

autoindex_exact_size off;

默认为 on,显示出文件的确切大小,单位bytes;

修改为off,显示出文件的大概大小,单位是kB或MB或GB

 

autoindex_localtime on;

默认为off,显示的文件时间为GMT时间。

修改为on,显示的文件时间为文件的服务器时间。

 

charset utf-8,gbk;

默认中文目录乱码,添加上解决乱码

例如:

1、当我们访问game.com时,打开首页

2、当我们访问game.com/gms时,会打开目录索引列表

在conf.d下修改ame.conf

server {
        listen 80;
        server_name game.com;

        location / {                            #访问http://game.com时,跳转导服务器/gms_sz下,寻找index.html
                root /home/wwwroot/gms_sz;    
                index index.php index.html;            

        }
        location /gms {                          #访问http://game.com/gms时,跳转到wwwroot/gms下,开启目录索引防止中文乱码,使用文件自己的时间戳,文件大小以单位的方式显示
                root /home/wwwroot;
               # index index.php index.html;
                #autoindex on;
                charset utf-8;
        }

}

 7、Nginx状态监控

1、ngx_http_stub_status_module 用于展示Nginx连接状态信息,需要 --with-http_stub_status_module模块支持

语法:

  Syntax:stub_status;

  Default:—

  Context:serverlocation

2、配置Nginx status

  location /nginx_status {

    stub_status;

    access_log off;  #关闭访问日志

  }

3、当使用浏览器访问http://ip/nginx_status

Active connections: 2 
server accepts handled requests
 34 34 66 
Reading: 0 Writing: 1 Waiting: 1 
Active connections    #当前活动连接数
accepts 34       #当前的总连接数TCP
handled 34       #成功的连接数TCP  
requests 64       #总的http请求数 


Reading          #请求
Writing          #响应
Waiting          #等待的请求,开启了keepalive

#注意,一次Tcp的连接数,可以发起多次http的请求,如下配置参数可验证
keepalive_timeout 0;  #类似于关闭长连接
keepalive_timeout 65; #65 s没有活动则断开连接

注意:
如果使用restart重置服务器,会清空所有的连接数
reload重载服务器,不会清空之前的连接数
通过状态监控,可以区分长连接和短链接
修改vim /etc/nginx/nginx.conf下
keepalive_timeout 0;  #将长连接变为短链接

8、Nginx访问控制
 
 基于ip的访问控制 http_access_module
1、Nginx基于IP的访问控制
    //允许配置语法
    Syntax:allow address | CIDR | unix: | all;
    Default:-
    Context:  httpserverlocationlimit_except
    //拒绝配置语法
    Syntax:deny address | CIDR | unix: | all;
    Default:—
    Context:httpserverlocationlimit_except
访问控制规则查看流程:
从上往下,依次匹配,满足就停止

企业中反问控制的思路:
先写允许,默认拒绝所有
先写拒绝,默认允许所有
例:

 


 只允许allow  ip 访问nginx_status,其它都拒绝访问

2、基于用户登录认证  http_auth_basic_module

  //配置语法:
  Syntax:auth_basic string | off;
  Default:
auth_basic off;
  Context:httpserverlocationlimit_except
  //用户密码记录配置文件
  Syntax: auth_basic_user_file file;
  Default: —
  Context: httpserverlocationlimit_except


  //需要安装依赖组件

[root@localhost nginx]# yum install httpd-tools

  [root@localhost nginx]# htpasswd -b -c /etc/nginx/.auth.conf cm 123456

 vim /etc/nginx/conf.d/game.conf

        location /gms {
                root /home/wwwroot;
                index index.php index.html;
                #autoindex on;
                charset utf-8;
                auth_basic "don't test!!!";
                auth_basic_user_file /etc/nginx/.auth.conf;  #和htpasswd -b -c /etc/nginx/.auth.conf cm 123456对应
        }

然后重载nginx测试:

 

 

9、Nginx访问限制

经常会遇到这种情况,服务器流量异常,负载过大等等,对于大流量恶意的攻击访问,会带来带宽的浪费,服务器压力,影响业务,往往考虑对同一个IP的连接数,并发数进行限制

ngx_http_limit_conn_module 模块可以根据定义的key来限制每个键值的连接数,如同一个IP来源的连接数。
limit_conn_module 连接频率限制
limit_req_module 请求频率限制


变量:
$binary_remote_addr  变量的长度是固定的4字节
$remote_addr      变量长度是7-15字节

1、Nginx连接限制配置
1)Nginx连接限制语法
Syntax:limit_conn_zone key zone=name:size;
Default:—
Context:http

Syntax:limit_conn zone number;
Default:—
Context:httpserverlocation


2)Nginx连接限制实战

  http {
  //http段配置连接限制,同一时刻只允许一个客户端IP连接
  limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
    ...
    server {
    ...
      location / {
      //同时刻只允许一个客户端IP连接
        limit_conn conn_zone 1;      

      }

    }
  }
3)使用ab工具进行压力测试
  //压力测试
  yum install -y httpd-tools
  ab -n 50 -c 20 http://127.0.0.1/index.html
2、Nginx请求限制配置实站

ngx_http_limit_req_module
1)Nginx请求限制语法

 

 

 

 

 

 2)Nginx请求限制实战

  http {
  //http段配置请求限制,rate限制速率,限制一秒钟最多一个IP请求
  limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
    ...
    server {
    ...
      location / {
      //
1r/s只接收一个请求,其余请求拒绝处理并返回错误码给客户端
        limit_req zone=
req_zone;
      //
请求超过1r/s,剩下的将被延迟处理,请求数超过burst定义的数量,多余的请求返回503  
        #
limit_req zone=req_zone burst=3 nodelay;
      }

    }
  }
3)使用ab工具进行压力测试
  //压力测试
  yum install -y httpd-tools
  ab -n 50 -c 20 http://127.0.0.1/index.html
3、Nginx连接限制没有请求限制有效
多个请求可以建立在一次的TCP连接之上,那么我们对请求的精度限制,当然比对一个连接限制会更加的有效
因为同一时刻只允许一个连接请求进入,但是同一时刻多个请求可以通过一个连接进入,所以请求限制才是比较优的解决方案



  
 
posted on 2021-01-07 20:58  草根920  阅读(516)  评论(0编辑  收藏  举报