(基础)NGINX 第二章 NGINX基础

本文详细介绍了NGINX的基本配置,包括全局配置、event模块、http模块等,并讲解了如何利用NGINX实现反向代理、负载均衡、URL重写等功能。此外,还介绍了NGINX的缓存配置及开启gzip的方法。

NGINX是什么

我们都听说过NGINX可以用来做反向代理服务器,其实它也可以做为图片缓存、正向代理等功能。作为一个高性能的反向代理服务器,主要有两个方面支持它的高性能,第一个是采用异步非阻塞处理机制,运用了操作系统的epoll模型。第二个是优秀的架构设计,基于Master-Worker的工作模式。

NGINX模块及配置

典型的web服务器NGINX的配置包括全局(main)模块,event模块、http模块。其中http模块是web服务器的核心模块,里边包含server模块(虚拟主机模块),server下包含location模块,如果有负载均衡功能,还可能包含upstream模块。如下图所示。
在这里插入图片描述

全局模块

#Nginx的worker进程运行用户以及用户组
#user  nobody nobody;
#Nginx开启的进程数
worker_processes  1;
#worker_processes auto;
#以下参数指定了哪个cpu分配给哪个进程,一般来说不用特殊指定。如果一定要设的话,用0和1指定分配方式.
#这样设就是给1-4个进程分配单独的核来运行,出现第5个进程是就是随机分配了。eg:
#worker_processes 4     #4核CPU 
#worker_cpu_affinity 0001 0010 0100 1000;
nets   
#定义全局错误日志定义类型,[debug|info|notice|warn|crit]
#error_log  logs/error.log  info;
#指定进程ID存储文件位置
#pid        logs/nginx.pid;
#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n的值保持一致。
#vim /etc/security/limits.conf
#  *                soft    nproc          65535
#  *                hard    nproc          65535
#  *                soft    nofile         65535
#  *                hard    nofile         65535
worker_rlimit_nofile 65535;

event模块

events {
    #use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
    use epoll;
    #每个进程可以处理的最大连接数,理论上每台nginx服务器的最大连接数为worker_processes*worker_connections。理论值:worker_rlimit_nofile/worker_processes
    #注意:最大客户数也由系统的可用socket连接数限制(~ 64K),所以设置不切实际的高没什么好处
    worker_connections  65535;    
    #worker工作方式:串行(一定程度降低负载,但服务器吞吐量大时,关闭使用并行方式,如下)
    #multi_accept on; 
}

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"';
    #定义日志的格式。后面定义要输出的内容。
    #1.$remote_addr 与$http_x_forwarded_for 用以记录客户端的ip地址;
    #2.$remote_user :用来记录客户端用户名称;
    #3.$time_local :用来记录访问时间与时区;
    #4.$request  :用来记录请求的url与http协议;
    #5.$status :用来记录请求状态;
    #6.$body_bytes_sent :记录发送给客户端文件主体内容大小;
    #7.$http_referer :用来记录从那个页面链接访问过来的;
    #8.$http_user_agent :记录客户端浏览器的相关信息
    #连接日志的路径,指定的日志格式放在最后。
    #access_log  logs/access.log  main;
    #只记录更为严重的错误日志,减少IO压力
    error_log logs/error.log crit;
    #关闭日志
    #access_log  off;
 
    #默认编码
    #charset utf-8;
    #服务器名字的hash表大小
    server_names_hash_bucket_size 128;
    #客户端请求单个文件的最大字节数
    client_max_body_size 8m;
    #指定来自客户端请求头的hearerbuffer大小
    client_header_buffer_size 32k;
    #指定客户端请求中较大的消息头的缓存最大数量和大小。
    large_client_header_buffers 4 64k;
    #开启高效传输模式。
    sendfile on;
    #防止网络阻塞
    tcp_nopush on;
    tcp_nodelay on;    
    #客户端连接超时时间,单位是秒
    keepalive_timeout 60;
    #客户端请求头读取超时时间
    client_header_timeout 10;
    #设置客户端请求主体读取超时时间
    client_body_timeout 10;
    #响应客户端超时时间
    send_timeout 10;
 
    #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
 
    #gzip模块设置
    #开启gzip压缩输出
    gzip on; 
    #最小压缩文件大小
    gzip_min_length 1k; 
    #压缩缓冲区
    gzip_buffers 4 16k;
    #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_http_version 1.0;
    #压缩等级 1-9 等级越高,压缩效果越好,节约宽带,但CPU消耗大
    gzip_comp_level 2;
    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
    gzip_types text/plain application/x-javascript text/css application/xml;
    #前端缓存服务器缓存经过压缩的页面
    gzip_vary on;

server模块

    #虚拟主机定义
    server {
        #监听端口
        listen       80;
        #访问域名
        server_name  localhost;
        #编码格式,若网页格式与此不同,将被自动转码
        #charset koi8-r;
        #虚拟主机访问日志定义
        #access_log  logs/host.access.log  main;
        #对URL进行匹配
        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;
        }
 
        #访问URL以.php结尾则自动转交给127.0.0.1
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        
        #php脚本请求全部转发给FastCGI处理
        # 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;
        #}
 
        #禁止访问.ht页面 (需ngx_http_access_module模块)
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
    
    #HTTPS虚拟主机定义
    # 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;
    #    }
    #}
    
   #vue配置
    server {
        listen       80;
        server_name  jcsd-cdn-monitor.jdcloud.com;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        root /root/dist;
 
        location / {
            try_files $uri $uri/ /index.html;
        }
 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

典型应用

反向代理

#以下配置追加在HTTP的全局变量中

#启动代理缓存功能
proxy_buffering on;
#nginx跟后端服务器连接超时时间(代理连接超时)
proxy_connect_timeout      5;
#后端服务器数据回传时间(代理发送超时)
proxy_send_timeout         5;
#连接成功后,后端服务器响应时间(代理接收超时)
proxy_read_timeout         60;
#设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffer_size          16k;
#proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
proxy_buffers              4 32k;
#高负荷下缓冲大小(proxy_buffers*2)
proxy_busy_buffers_size    64k;
#设定缓存文件夹大小,大于这个值,将从upstream服务器传
proxy_temp_file_write_size 64k;
#反向代理缓存目录
proxy_cache_path /data/proxy/cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=1g;
#levels=1:2 设置目录深度,第一层目录是1个字符,第2层是2个字符
#keys_zone:设置web缓存名称和内存缓存空间大小
#inactive:自动清除缓存文件时间。
#max_size:硬盘空间最大可使用值。
#指定临时缓存文件的存储路径(必须在同一分区)
proxy_temp_path /data/proxy/temp;
 
#服务配置
server {
    #侦听的80端口
    listen       80;
    server_name  localhost;
    location / {
        #反向代理缓存设置命令(proxy_cache zone|off,默认关闭所以要设置)
        proxy_cache cache_one;
        #对不同的状态码缓存不同时间
        proxy_cache_valid 200 304 12h;
        #设置以什么样参数获取缓存文件名
        proxy_cache_key $host$uri$is_args$args;
        #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   
        #代理设置
        proxy_pass   http://IP; 
        #文件过期时间控制
        expires    1d;
    }
    #配置手动清楚缓存(实现此功能需第三方模块 ngx_cache_purge)
    #http://www.123.com/2017/0316/17.html访问
    #http://www.123.com/purge/2017/0316/17.html清楚URL缓存
    location ~ /purge(/.*) {
        allow    127.0.0.1;
        deny    all;
        proxy_cache_purge    cache_one    $host$1$is_args$args;
    }
    #设置扩展名以.jsp、.php、.jspx结尾的动态应用程序不做缓存
    location ~.*\.(jsp|php|jspx)?$ { 
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   
        proxy_pass http://IP;
    }

负载均衡

#负载均衡服务器池
upstream my_server_pool {
    #调度算法
    #1.轮循(默认)(weight轮循权值)
    #2.ip_hash:根据每个请求访问IP的hash结果分配。(会话保持)
    #3.fair:根据后端服务器响应时间最短请求。(upstream_fair模块)
    #4.url_hash:根据访问的url的hash结果分配。(需hash软件包)
    #参数:
    #down:表示不参与负载均衡
    #backup:备份服务器
    #max_fails:允许最大请求错误次数
    #fail_timeout:请求失败后暂停服务时间。
    server 192.168.1.109:80 weight=1 max_fails=2 fail_timeout=30;
    server 192.168.1.108:80 weight=2 max_fails=2 fail_timeout=30;
}
#负载均衡调用
server {
    ...
    location / {
    proxy_pass http://my_server_pool;
    }
}

URL重写

#根据不同的浏览器URL重写
if($http_user_agent ~ Firefox){
rewrite ^(.*)$  /firefox/$1 break; 
}
if($http_user_agent ~ MSIE){
rewrite ^(.*)$  /msie/$1 break; 
}
 
#实现域名跳转
location / {
    rewrite ^/(.*)$ https://web8.example.com$1 permanent;
}

IP限制

#限制IP访问
location / {
    deny 192.168.0.2;
    allow 192.168.0.0/24;
    allow 192.168.1.1;
    deny all;
}

NGINX重启

#启动nginx
nginx 
#关闭nginx
nginx -s stop
#平滑重启
kill -HUP `cat /usr/local/nginx/logs/nginx.pid`

NGINX缓存配置

1)客户端的缓存(一般指浏览器的缓存)。
打开nginx.conf,使用 cat /usr/local/etc/nginx/nginx.conf

server {
  location ~* \.(html)$ {
    access_log off;
    add_header  Cache-Control  max-age=no-cache;
  }

  location ~* \.(css|js|png|jpg|jpeg|gif|gz|svg|mp4|ogg|ogv|webm|htc|xml|woff)$ {
    # 同上,通配所有以.css/.js/...结尾的请求
    access_log off;
    add_header    Cache-Control  max-age=360000;
  }
}

如上配置解析含义如下:
~* 的含义是:通配任意字符(且大小写不敏感),\转义字符,因此 ~* .(html)$的含义是:匹配所有以.html结尾的请求
access_log off; 的含义是 关闭日志功能。
add_header Cache-Control max-age=no-cache; 的含义:html文件不设置强制缓存时间,协商缓存,使用 Last-Modified。no-cache 会发起往返通信来验证缓存的响应,但如果资源未发生变化,则不会下载,返回304。

如果是反向代理后的页面,如上设置是不生效的。比如说我node起了一个服务,然后通过访问nginx反向代理的方式代理到我node服务来,上面的配置是不生效的。

2)服务端的缓存(使用proxy-cache实现的)。

客户端的缓存

客户端缓存有两种实现方式,包括协商缓存和强缓存。

服务端的缓存

解决nginx反向代理缓存不起作用的问题

比如我的node服务端口是7878端口。nginx需要如下配置:

server {
  listen  8081;
  server_name  xxx.abc.com;
  location / {
    proxy_pass http://localhost:7878;
    add_header  Cache-Control  max-age=no-cache;
  }
}
  1. 如果我们要添加缓存功能的话,需要创建一个用于存放缓存文件的文件夹。比如我们这里使用 /data/nuget-cache。

在/usr/local/etc/nginx目录下新建。比如使用命令:mkdir /data/nuget-cache。

  1. 然后我们需要在nginx.conf的http设置部分添加 proxy_cache_path的设置。
    3)我们还需要在server设置部分添加代理设置。
http {
  // ..... 其他的配置
  proxy_cache_path  /data/nuget-cache levels=1:2 keys_zone=nuget-cache:20m max_size=50g inactive=168h;
  server {
    listen  8081;
    server_name  xxx.abc.com;
    location / {
      proxy_pass http://localhost:7878;
      add_header  Cache-Control  max-age=no-cache;
      proxy_cache nuget-cache;
      proxy_cache_valid 168h;
      proxy_ignore_headers Set-Cookie Cache-Control;
      proxy_hide_header Cache-Control;
      proxy_hide_header Set-Cookie;
    }
  }
}

但是如上写法看起来很繁琐,因此我们可以使用include命令把文件包含进来,因此我在 /usr/local/etc/nginx 目录下新建一个 nginx_proxy.conf 配置文件,把上面的 proxy相关的配置放到该文件里面,如下所示:
在这里插入图片描述
然后我们的配置就变成如下了:

http {
  // ..... 其他的配置
  proxy_cache_path  /data/nuget-cache levels=1:2 keys_zone=nuget-cache:20m max_size=50g inactive=168h;
  include nginx_proxy.conf;
  server {
    listen  8081;
    server_name  xxx.abc.com;
    location / {
      proxy_pass http://localhost:7878;
      add_header  Cache-Control  max-age=no-cache;
    }
  }
}

如上是对页面使用协商缓存的,但是对于图片,css, 或js这样的,我想使用强制缓存,因此对于其他的类型文件我们统一如下这样处理:

server {
  listen       8081;
  server_name  xxx.abc.com;
  location / {
    proxy_pass http://localhost:7878;
    add_header  Cache-Control  max-age=no-cache;
  }
  location ~* \.(css|js|png|jpg|jpeg|gif|gz|svg|mp4|ogg|ogv|webm|htc|xml|woff)$ {
    access_log off;
    add_header Cache-Control "public,max-age=30*24*3600";
    proxy_pass http://localhost:7878;
  }
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   html;
  }
}

如上css或js文件等缓存的时间是30天。使用的是max-age强制缓存。因此如上,如果是页面第二次访问的话,会返回304,如下所示:

在这里插入图片描述

NGINX开启gzip

在http下加上上面的gzip代码。

http {
  # 开启gzip
  gzip on;

  # 启用gzip压缩的最小文件;小于设置值的文件将不会被压缩
  gzip_min_length 1k;

  # gzip 压缩级别 1-10 
  gzip_comp_level 2;

  # 进行压缩的文件类型。

  gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

  # 是否在http header中添加Vary: Accept-Encoding,建议开启
  gzip_vary on;
}

我们查看响应头会看到gzip这样的压缩,如下所示。
在这里插入图片描述

NGINX配置https

参考:https://blog.csdn.net/weixin_37264997/article/details/84525444

参考

淘宝nginx学习手册:http://tengine.taobao.org/book/index.html
NGINX基本操作:https://blog.csdn.net/HzSunshine/article/details/63687054

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值