nginx 简介

2018-06-27  本文已影响0人  林ze宏

简介

nginx是轻量级、高性能的http和反向代理的web服务器。

安装

下载官网:http://nginx.org/en/download.html(右边选择要安装的版本复制链接地址,直接在Linux中直接 wget )

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

  cd /usr/local/src/
  wget http://nginx.org/download/nginx-1.4.2.tar.gz
  tar zxvf nginx-1.4.2.tar.gz

  cd nginx-1.4.2
  ./configure --prefix=/usr/local/nginx
  make && make install

到这里,恭喜您,安装成功了。

如果安装出现以下错误:

**./configure: error: the HTTP gzip module requires the zlib library. You can either disable the module by using –without-http_gzip_module option, or install the zlib library into the system, or build the zlib library statically from the source with nginx by using –with-zlib=<path> option.**

则需要安装 “zlib-devel” 即可。SSH 执行以下命令:

代码如下 复制代码

yum install -y zlib-devel

缺少 c++ 编译器的原因

yum install -y gcc gcc-c++

指向源码包,不是编译安装后的包,所以

./configure –prefix=/export/lnmp/nginx-1.4.7 –with-pcre=../pcre-8.34

启动

安装完成后,紧接着启动

  cd /usr/local/nginx, 看到如下4个目录
  ./
   ....conf 配置文件  
   ... html 网页文件
   ...logs  日志文件 
   ...sbin  主要二进制程序

[root@localhost nginx]# ./sbin/nginx

如果出现:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
....
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

说明:不能绑定80端口,80端口已经被占用
(有时是自己装了apache,nginx等,还有更多情况是操作系统自带了apache并作为服务启动)
解决: 把占用80端口的软件或服务关闭即可.

执行:(查看80端口暂用的程序,kill)
[root@localhost nginx]# netstat -antp(查看进程号和对应的程序名)
[root@localhost nginx]# pkill -9 进程号

信号量

http://nginx.org/en/docs/control.html

信号量
查看Nginx的进程号
ps -aux | grep nginx

具体语法:
Kill -信号选项 nginx的主进程号
如:Kill -HUP 4873

由于Nginx的进程号每次都会改变,Nginx把进程号存在于log/nginx.pid,所以,可以利好顿号 cat 
如:
[root@iZ2zeb5jdmrubzqdcwo2biZ nginx]# kill -HUP `cat ./logs/nginx.pid`
查看帮忙命令
[root@localhost nginx]# ./sbin/nginx -h
检测配置是否有无问题  
[root@localhost nginx]# ./sbin/nginx -t

[root@localhost nginx]# ./sbin/nginx -s reload 重读配置文件 相当于 -HUP
[root@localhost nginx]# ./sbin/nginx -s stop 停止 相当于 -INT
[root@localhost nginx]# ./sbin/nginx -s quit 优雅停止 相当于 -QUIT
[root@localhost nginx]# ./sbin/nginx -s reopen 重新打开日志 相当于 -USR1

基于域名、端口、IP配置的server

域名本地测试时,可以在 host 中配置。

nginx.conf:实际项目

#user  nobody;
// 有1个工作的子进程,可以自行修改,但太大无益,因为要争夺CPU,一般设置为 CPU数*核数
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 {
// 一般是配置nginx连接的特性
// 如1个word能同时允许多少连接
 worker_connections  1024; // 这是指 一个子进程最大允许连1024个连接

}


http { //这是配置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;

// gzip 压缩
    gzip on;
    gzip_min_length 10k;
    gzip_buffers 32 8k;
    gzip_comp_level 6;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif 
    gzip_vary off;


    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

// 前端项目打包后,放在nginx/html目录下,Nginx默认从Nginx安装的根目录开始寻找
// 前端项目配置的访问url,斜杆 / ,指直接使用 localhost(或者服务器的IP) 访问
        location / {
           try_files $uri /index.html;
            root   html;
            index  index.html index.htm;
        }

//  后台打的jar包,前端调用后台的所有api接口,都是以 /console 开头的。
// 前端 ( location / ) 访问后台的api,会被转这个( location /console)这个 location 进行处理,后台通过启用监听的端口,jar包通过nohup 启动整个服务,就可以让前端调到对应的接口
        location /console {
            proxy_pass http://127.0.0.1:8090/console;
        }

        location /consoleTest {
            proxy_pass http://127.0.0.1:18090/consoleTest;
        }

        location /vcs/sensorynode {
            proxy_pass http://127.0.0.1:9090/vcs/sensorynode;
        }
     
        location /sensorynode {
            proxy_pass http://127.0.0.1:9090/vcs/sensorynode;
        }

        location /vcs/picsearch {
            proxy_pass http://127.0.0.1:19090/vcs/picsearch;
        }
 
    }

}

server 配置例子

例子1:
  server {
        listen       80;
        server_name  zehomg.com; //通过域名,测试公网没有这个域名,可以通过本地配置 host 进行测试。
        location / {
            try_files $uri /index.html;
            root   zehong; // 项目存放的目录,从Nginx根目录开始寻找,这里配置的就是 nginx/zehong
            index  index.html index.htm;
        }
  }

例子2:
  server {
        listen       2020;
        server_name  192.168.1.21; //通过IP
        location / {
            try_files $uri /index.html;
            root   /var/www/ip; // 项目存放的目录,是可以随便改的
            index  index.html index.htm;
        }
  }

日志管理

server {
  listen  80;
  server_name  zehong.com;
  location / {
    root zehong;
    index index.html;
  }
  
access_log logs/zehong.com.access.log main;

}


说明:
这说明 该server, 它的访问日志的文件是  logs/zehong.com.access.log ,
使用的格式”main”格式.

默认的日志格式说明: main 格式
     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';

默认的main日志格式,记录这么几项
远程IP- 远程用户/用户时间 请求方法(如GET/POST) 请求体body长度 referer来源信息
http-user-agent用户代理/蜘蛛 ,被转发的请求的原始IP

http_x_forwarded_for:在经过代理时,代理把你的本来IP加在此头信息中,传输你的原始IP

实际应用: shell+定时任务+nginx信号管理
分析思路: 
凌晨00:00:01,把昨天的日志重命名,放在相应的目录下
再USR1信息号控制nginx重新生成新的日志文件

具体脚本:runlog.sh
#!/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
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`

定时任务
Crontab 编辑定时任务
01 00 * * * /xxx/path/runlog.sh  每天0时1分(建议在02-04点之间,系统负载小;01 00 * * * 表示分 时 日 月 周)

定时任务具体执行:查看定时任务相关知识
crontab -e


location

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

location 的语法:中括号可以不写任何参数,此时称为一般匹配
location [=|~|~*|^~] patt {

}

大类型可以分为3种:
location = patt {} [精准匹配]

location patt{} [一般匹配]

location ~ patt{} [正则匹配]


如何发挥作用?:
1:首先看有没有精准匹配,如果有,则停止匹配过程.

location = patt {
 config A
}
如果 $uri == patt,匹配成功,使用configA

例子:
 location = / {  // 精准
   root /var/www/html/;
   index index.htm index.html;
 }

 location / {  // 一般
   root /usr/local/nginx/html;
   index index.html index.htm;
 }

如果访问  [http://xxx.com](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 ~ image {
 root /var/www/;
 index index.html;
}

如果我们访问(http://xx.com/image/logo.png)

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

正则表达式的成果将会使用.
图片真正会访问 /var/www/image/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’匹配的更长,因此使用之.;

也就是一般匹配哪个长度较长,就用哪个。
1:先判断精准命中,如果命中,立即返回结果并结束解析过程
2:判断普通命中,如果有多个命中,“记录”下来“最长”的命中结果
(注意:记录但是不结束,最长的为准)
3:继续判断正则表达式的解析结果,按匹配里的正则表达式顺序为准,
由上到下开始匹配,一旦匹配成功一个,立即返回结果,并结束解析过程。

延伸分析:
1:普通命中顺序无所谓,是因为按照命中的长度来确定的
2:正则命中跟顺序有关,是按照配置的从上往下匹配,只要匹配一个成功,就直接返回。

rewrite


gzip

http://nginx.org/en/docs/http/ngx_http_gzip_module.html

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资源的.
比较小的文件不必压缩

上下文:http, server, location, if in location;一般我们配置在server中

一般项目需要配置的几个选项:
gzip on;
gzip_buffers 32 4k;
gzip_comp_level 6;
gzip_min_length 4000;
gzip_types text/css text/xml application/x-javascript;


nginx的缓存设置:expires

格式  expires 30s;
      expires 30m;
      expires 2h;
      expires 30d;

对图片进行缓存例子:
location ~ * \.(jpg | jpeg | gif | png) {
  expires 1d;
}



Nginx反向代理与负载均衡

location ~ \.php$ {
  proxy_pass http://192.168.1.110:8080
}
说明:浏览器请求为PHP的时候,Nginx根据location配置的,通过proxy_pass 反向代理到具体的后台请求地址。

location /console {
 proxy_pass http://127.0.0.1:8090/console;
}
说明:如前后端分离,这里浏览器调用以console 开头的api时候,就会反向代理到后台工程(也就是后台打的jar包)

后台jar启动停止脚本

后台启动的jar包shell脚本

start.sh:

#!/bin/bash

PROJECT_NAME=console.jar

pid=`ps -ef|grep $PROJECT_NAME |grep -v "grep" |awk '{print $2}'`

if [ $pid ] ; then

   echo "console is already running and pid=$pid"

else

   echo "start success to start $PROJECT_NAME ...."

   nohup java -jar $PROJECT_NAME >/dev/null聽2>nohup.out &

fi

后台停止的jar包shell脚本

stop.sh:

#!/bin/bash

PROJECT_JAR=console.jar
PROJECT_NAME=console
PROJECT_LOG=console.*.log

pid=`ps -ef|grep $PROJECT_JAR | grep -v "grep" | awk '{print $2}'`

log_pid=`ps -ef|grep $PROJECT_LOG | grep -v "grep" | awk '{print $2}'`

if [ $pid ] ; then

   echo "Stopping the $PROJECT_NAME , please wait ..."

   kill $pid
   
   if [ $log_pid ] ; then

       kill $log_pid
   
   fi
   
   echo "stop the $PROJECT_NAME successfully"

else 
  
   echo "$PROJECT_NAME is already stopped"

fi
   

后台jar目录

补充

window nginx

启动,直接执行 nginx.exe,或者在 git bash 窗口,执行 nginx.exe,然后,浏览器直接访问 http://localhost/

启动 成功

代理缓存:

proxy_cache_path cache levels=1:2 keys_zone=my_cache:10m

server {
  listen  80;
  server_name test.com;

  location / {
    proxy_cache my_cache;
    proxy_pass http://127.0.0.1:8888;
    proxy_set_header Host $host;
  }
}

说明:
1:nginx 的缓存是从磁盘读取的,速度相对比较慢,可以优化从内存读取;

2:nginx 缓存的主要作用为,只要浏览器访问过一次之后,不同浏览器访问,都可以使用代理服务器的缓存;

上一篇下一篇

猜你喜欢

热点阅读