温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nginx安装配置

发布时间:2020-07-21 20:03:03 来源:网络 阅读:904 作者:80后小菜鸟 栏目:建站服务器


nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器,nginx是由igor sysoev为俄罗斯访问量第二的Rambler.ru站点开发的。


1、nginx安装与配置

下载地址:http://nginx.org/download/nginx-1.12.1.tar.gz

安装准备:nginx依赖于pcre库,需要先安装pcre pcre-devel

yum install pcre pcre-devel -y
mkdir /root/tools
cd /root/tools
wget http://nginx.org/download/nginx-1.12.1.tar.gz
tar zxf nginx-1.12.1.tar.gz 
cd nginx-1.12.1
useradd -s /sbin/nologin nginx -M
./configure \
--user=nginx \
--group=nginx \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_stub_status_module
make && make install
echo $?
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/nginx
cd /usr/local/nginx

[root@localhost nginx]# tree

.
├── conf   #配置文件
│   ├── fastcgi.conf
│   ├── fastcgi.conf.default
│   ├── fastcgi_params
│   ├── fastcgi_params.default
│   ├── koi-utf
│   ├── koi-win
│   ├── mime.types
│   ├── mime.types.default
│   ├── nginx.conf
│   ├── nginx.conf.default
│   ├── scgi_params
│   ├── scgi_params.default
│   ├── uwsgi_params
│   ├── uwsgi_params.default
│   └── win-utf
├── html  #网页文件
│   ├── 50x.html
│   └── index.html
├── logs   #日志文件
└── sbin   #主要二进制程序
    ├── nginx


1)nginx 信号控制:

TERM,INT    quick shutdown

QUIT        优雅的关闭进程,即等待请求结束后再关闭

HUP         改变配置文件,平滑的重读配置文件

USR1        重读日志,在日志按月、日分隔时使用

USR2        平滑升级

WINCH       优雅关闭进程,配合USR2来进行升级


启动nginx:

/usr/local/nginx/sbin/nginx

重启动nginx:

kill -QUIT `cat /usr/local/nginx/logs/nginx.pid` && /usr/local/nginx/sbin/nginx

重新加载配置文件:

kill -HUP `cat /usr/local/nginx/logs/nginx.pid` 

/usr/local/nginx/sbin/nginx -s reload

停止nginx:

kill -INT `cat /usr/local/nginx/logs/nginx.pid`

/usr/local/nginx/sbin/nginx -s stop/quit

重读日志文件:

kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`

/usr/local/nginx/sbin/nginx -s reopen


2)nginx配置文件:

access_log日志格式变量说明:


$remote_addr  #远程客户端IP

$remote_user #客户端用户信息

$time_local # 本地时间

$request #请求方式,路径和版本

$status  #响应状态

$body_bytes_sent  #发送到客户端的字节数

$http_referer #上一次页面来自哪

$http_user_agent #客户端代理信息

$http_x_forwarded_for #代理服务器转发地址

#user  nobody;   #运行用户
worker_processes  1; #工作进程,一般为CPU数*核数
#全局错误日志
#error_log  logs/error.log; 
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#PID文件
#pid        logs/nginx.pid;
events {
     use   epoll;  #epoll是多路复用IO(I/OMultiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
  #一般是配置nginx链接的特性,如一个worK能同时允许多个个链接
    worker_connections  1024; #指一个进程最大允许1024个链接
}
http {   #配置http服务器的主要段
    include       mime.types; #设定mime类型,类型由mime.type文件定义
    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  logs/access.log  main;
    sendfile        on; 
 #指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;  #连接超时时间
    #gzip  on;   #开启gzip压缩
     #设定请求缓冲
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
    #设定负载均衡的服务器列表
     upstream mysvr {
    #weigth参数表示权值,权值越高被分配到的几率越大
    #本机上的Squid开启3128端口
    server 192.168.8.1:3128 weight=5;
    server 192.168.8.2:80  weight=1;
    server 192.168.8.3:80  weight=6;
    }
    server {   #虚拟主机
        listen       80;  #侦听80端口
        server_name  localhost; #定义使用www.xx.com访问
        #charset koi8-r;
        #设定本虚拟主机的访问日志
        #access_log  logs/host.access.log  main;
        #默认请求
        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;
        }
        #反向代理
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        #转发PHP动态页面给PHP程序处理
        #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;
}

3)实际应用: shell+定时任务+nginx信号管理,完成日志按日期存储

分析思路: 

凌晨00:00:01,把昨天的日志重命名,放在相应的目录下

再USR1信息号控制nginx重新生成新的日志文件

具体脚本:

#!/bin/bash
base_path='/usr/local/nginx/logs'
log_path=$(date -d yesterday +"%Y%m")
day=$(date -d yesterday +"%d")
mkdir -p $base_path/$log_path
mv $base_path/access.log $base_path/$log_path/access_$day.log
#echo $base_path/$log_path/access_$day.log
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`

定时任务

Crontab 编辑定时任务

01 00 * * * /xxx/path/b.sh  每天0时1分(建议在02-04点之间,系统负载小)


4)location 语法

location 有”定位”的意思, 根据Uri来进行不同的定位.

在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上.

比如, 碰到.php, 如何调用PHP解释器?  --这时就需要location

location 的语法

location [=|~|~*|^~] patt {

}

中括号可以不写任何参数,此时称为一般匹配

也可以写参数

因此,大类型可以分为3种

location = patt {} [精准匹配]

location patt{}  [一般匹配]

location ~ patt{} [正则匹配]


如何发挥作用?:

首先看有没有精准匹配,如果有,则停止匹配过程.

location = patt {
    config A
}
如果 $uri == patt,匹配成功,使用config A
   location = / {
              root   /var/www/html/;
             index  index.htm index.html;
        }
         
  location / {
             root   /usr/local/nginx/html;
            index  index.html index.htm;
  }

如果访问  http://xxx.com/

定位流程是 

1: 精准匹配中 ”/”   ,得到index页为  index.htm

2: 再次访问 /index.htm , 此次内部转跳uri已经是”/index.htm” , 

根目录为/usr/local/nginx/html

3: 最终结果,访问了 /usr/local/nginx/html/index.htm

正则也来参与.

location / {
            root   /usr/local/nginx/html;
            index  index.html index.htm;
        }
location ~ p_w_picpath {
           root /var/www/p_w_picpath;
           index index.html;
}

如果我们访问  https://cache.yisu.com/upload/information/20200309/32/37286.jpg

此时, “/” 与”/p_w_picpath/logo.png” 匹配

同时,”p_w_picpath”正则 与”p_w_picpath/logo.png”也能匹配,谁发挥作用?

正则表达式的成果将会使用.

图片真正会访问 /var/www/p_w_picpath/logo.png 

location / {
             root   /usr/local/nginx/html;
             index  index.html index.htm;
         }
 
location /foo {
            root /var/www/html;
             index index.html;
}

我们访问 http://xxx.com/foo

 对于uri “/foo”,   两个location的patt,都能匹配他们

即 ‘/’能从左前缀匹配 ‘/foo’, ‘/foo’也能左前缀匹配’/foo’,

此时, 真正访问 /var/www/html/index.html 

原因:’/foo’匹配的更长,因此使用之.;


5)rewrite 重写

重写中用到的指令

if  (条件) {}  设定条件,再进行重写 

set #设置变量

return #返回状态码 

break #跳出rewrite

rewrite #重写

If  语法格式

If 空格 (条件) {

    重写模式

}


条件又怎么写?

答:3种写法

1: “=”来判断相等, 用于字符串比较

2: “~” 用正则来匹配(此处的正则区分大小写)

   ~* 不区分大小写的正则

3: -f -d -e来判断是否为文件,为目录,是否存在.

例子:

            if  ($remote_addr = 192.168.1.100) {
                return 403;
            }
 if ($http_user_agent ~ MSIE) {
                rewrite ^.*$ /ie.htm;
                break; #(不break会循环重定向)
 }
             if (!-e $document_root$fastcgi_script_name) {
                rewrite ^.*$ /404.html break;
            }

注, 此处还要加break,以 xx.com/dsafsd.html这个不存在页面为例,我们观察访问日志, 日志中显示的访问路径,依然是GET /dsafsd.html HTTP/1.1

提示: 服务器内部的rewrite和302跳转不一样. 跳转的话URL都变了,变成重新http请求404.html, 而内部rewrite, 上下文没变,就是说 fastcgi_script_name 仍然是 dsafsd.html,因此 会循环重定向.set 是设置变量用的, 可以用来达到多条件判断时作标志用.达到apache下的 rewrite_condition的效果

如下: 判断IE并重写,且不用break; 我们用set变量来达到目的

if ($http_user_agent ~* msie) {
                set $isie 1;
            }
            if ($fastcgi_script_name = ie.html) {
                set $isie 0;
            }
            if ($isie 1) {
                rewrite ^.*$ ie.html;
            }

Rewrite语法

Rewrite 正则表达式  定向后的位置 模式

Goods-3.html ---->Goods.php?goods_id=3
goods-([\d]+)\.html ---> goods.php?goods_id =$1  
location /ecshop {
index index.php;
rewrite goods-([\d]+)\.html$ /ecshop/goods.php?id=$1;
rewrite article-([\d]+)\.html$ /ecshop/article.php?id=$1;
rewrite category-(\d+)-b(\d+)\.html /ecshop/category.php?id=$1&brand=$2;
注意:用url重写时, 正则里如果有”{}”,正则要用双引号包起来


6)gzip压缩

原理:浏览器---请求----> 声明可以接受 gzip压缩 deflate压缩 compress sdch压缩

http协议的角度看--请求头 声明 acceopt-encoding: gzip deflate sdch (是指压缩算法,其中sdchgoogle倡导的一种压缩方式,目前支持的服务器尚不多)服务器-->回应---把内容用gzip方式压缩---->发给浏览器浏览<-----解码gzip-----接收gzip压缩内容----


gzip配置的常用参数

gzip on|off;  #是否开启gzip

gzip_buffers 32 4K| 16 8K #缓冲(压缩在内存中缓冲几块? 每块多大?)

gzip_comp_level [1-9] #推荐6 压缩级别(级别越高,压的越小,越浪费CPU计算资源)

gzip_disable #正则匹配UA 什么样的Uri不进行gzip

gzip_min_length 200 # 开始压缩的最小长度(再小就不要压缩了,意义不在)

gzip_http_version 1.0|1.1 # 开始压缩的http协议版本(可以不设置,目前几乎全是1.1协议)

gzip_proxied          # 设置请求者代理服务器,该如何缓存内容

gzip_types text/plain application/xml # 对哪些类型的文件用压缩 txt,xml,html ,css

gzip_vary on|off  # 是否传输gzip压缩标志


注意:图片/mp3这样的二进制文件,不必压缩

因为压缩率比较小, 比如100->80字节,而且压缩也是耗费CPU资源的.比较小的文件不必压缩


7)nginx的缓存设置  提高网站性能

对于网站的图片,尤其是新闻站, 图片一旦发布, 改动的可能是非常小的.我们希望能否在用户访问一次后, 图片缓存在用户的浏览器端,且时间比较长的缓存.

可以, 用到 nginx的expires设置 .

nginx中设置过期时间,非常简单,在location或if段里,来写.

格式:expires 30s;  

      expires 30m;

      expires 2h;

      expires 30d;

(注意:服务器的日期要准确,如果服务器的日期落后于实际日期,可能导致缓存失效)

另: 304 也是一种很好的缓存手段

原理是: 服务器响应文件内容是,同时响应etag标签(内容的签名,内容一变,他也变), 和 last_modified_since 2个标签值

浏览器下次去请求时,头信息发送这两个标签, 服务器检测文件有没有发生变化,如无,直接头信息返回 etag,last_modified_since

浏览器知道内容无改变,于是直接调用本地缓存.

这个过程,也请求了服务器,但是传着的内容极少.

对于变化周期较短的,如静态html,js,css,比较适于用这个方式


8)nginx反向代理服务器+负载均衡

用nginx做反向代理和负载均衡非常简单,

支持两个用法 1个proxy, 1个upstream,分别用来做反向代理,和负载均衡

upstream负载平衡机制:

轮询-向应用服务器的请求以循环方式分发:(默认配置为轮询)

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

最少连接 - 下一个请求被分配给具有最少数量的活动连接的服务器:

 upstream myapp1 {
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

ip-hash - 哈希函数用于确定下一个请求应该选择哪个服务器(基于客户端的IP地址)。

upstream myapp1 {
    ip_hash;
    server srv1.example.com;
    server srv2.example.com;
    server srv3.example.com;
}

upstream参数说明:

weight=1  #服务器的权重,越大越高,默认为1

max_conns=1 #限制与代理服务器同时活动链接的最大值,默认为0

max_fails=1 #与服务器连接失败的次数内将服务器变为不可用,与fail_timeout一起使用,默认为1

fail_timeout=10 #指定次数连接不成功内考虑服务器不可用大时间

backup #将服务器标记为备份服务器

down  #将服务器标记为永久不可用

以反向代理为例, nginx不自己处理php的相关请求,而是把php的相关请求转发给apache来处理.

反向代理后端如果有多台服务器,自然可形成负载均衡,

但proxy_pass如何指向多台服务器?

把多台服务器用upstream指定绑定在一起并起个组名,然后proxy_pass指向该组:

将图片服务器做反向代理和负载均衡:

#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;
}
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"';
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    upstream imagserver{     #配置负载均衡服务器
  server 172.16.32.100:81 weight=1 max_fails=3 fail_timeout=10;
  server 172.16.32.100:82 weight=1 max_fails=3 fail_timeout=10;
}
    server {
listen81;
server_namelocalhost;
location / {
  root html;
  index index.php index.html index.htm;
  access_log logs/81_access.log main; 
}
    }
    server {
listen82;
server_namelocalhost;
location / {
  root html;
  index index.php index.html index.htm;
  access_log logs/82_access.log main;
}
    }
    server {
        listen       80;
        server_name  localhost;
    gzip  on;
    gzip_buffers 32 4k;
    gzip_comp_level 6;
    gzip_types text/plain p_w_picpath/jpeg application/xml;
    gzip_vary on;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.php index.html index.htm;
        }
location ~* \.(jpg|jpeg|gif|png){   #配置反向代理,将图片请求转发到服务器组
    proxy_set_header X-Forwarded-For $remote_addr; #将客户端请求IP传递到代理服务器日志$http_x_forwarded_for
    proxy_pass  http://imagserver;
}
        #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;
        }
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           html;
            proxy_set_header X-Forwarded-For $remote_addr;
            fastcgi_pass   127.0.0.1:9000;
            include        fastcgi.conf;
        }
}

---------------------------------end-------------------------------------------------------

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI