Nginx

时间:2022-06-10
本文章向大家介绍Nginx,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Nginx

什么是Nginx?

nginx是一个异步框架的Web服务器,也可以用作反向代理、负载平衡器和HTTP缓存。

Nginx服务器的优点

作为Web服务器:

相比Apache,Nginx使用更少资源,支持更多的并发连接,体现更高的效率。Nginx能够支持高达50 000个并发连接数的响应。

作为负载均衡服务器:

Nginx既可以在内部支持rails和PHP(Web应用开发框架),也可以支持作为HTTP代理服务器对外进行服务。Nginx用C编写,不论是系统资源开销还是CPU使用效率都比Perlbal要好的多

作为邮件代理服务器:

Nginx同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目录的之一也是作为邮件代理服务器)

Nginx安装非常简单,配置文件非常简洁

Nginx的编译安装

下载Nginx的源码包

直接去官网(www.nginx.org)查找源码包,直接复制链接地址下载,我们一般选择stable(稳定版),不选择最新版本

cd /opt
crul -O http://nginx.org/download/nginx-0.5.38.tar.gz

安装前的准备

需要安装pcre和pcre-devel (因为nginx有个rewrite功能伪静态,重写)需要使用pcre的libraries库文件。
yum -y install pcre pcre-devel
安装openssl因为我们后面启动了一个https的加密传输协议,所以也需要这个
yum -y install openssl openssl-devel
创建一个虚拟用户给Nginx使用
useradd -M -s /sbin/nologin web

解压编译安装

进到目录里面我们进行解压,然后./configure编译安装,编译成功后make 、make install安装

cd /opt
tar xf nginx-0.5.38.tar.gz
cd nginx-0.5.38
./configure --prefix=/usr/local/ nginx-0.5.38 --user=web --group=web --with-http_stub_status_module --with-http_ssl_module
#--prefix                           安装指定位置,我们最好加上一个版本号,然后做个软连接,为了以后能更轻松的升级版本
#--user --group                     指定nginx运行的时候使用的是那个虚拟用户的身份
#--with-http_stub_status_module     状态模块
#--with-http_ssl_module             https加密模块
echo $?                             查看编译是否正确
make && make install
echo $?                             如果返回值为0 我们编译安装成功

然后生成一个软链接,方便以后我们的nginx升级

ln -s /usr/local/nginx-0.5.38/ /usr/local/nginx

把nginx执行命令的路径放入到PATH路径里面去

export PATH=/usr/local/nginx/sbin:$PATH
echo "export PATH=/usr/local/nginx/sbin:$PATH" >>/root/.bash_profile 
source /root/.bash_profile

然后使用nginx命令来启动nginx服务

nginx
netstat -ntalp | grep nginx
[root@WNginx01_7 logs]# netstat -ntalp | grep nginx
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      1296/nginx

<!-- more -->能看到这个地方就说明我们nginx服务启动正常了

到浏览器里面输入Nginx服务器的ip地址

<!-- more -->能看到这个句话就说名我nginx的启动已经正常,最基本的nginx,最基本的web服务启动成功了。

Nginx的命令行参数

-c 指定配置文件,来取代默认的配置文件

-t 不运行,仅仅是测试一下nginx的配置文件语法是否有问题

[root@WNginx01_7 conf]# nginx -t 
2018/08/24 10:32:51 [info] 9703#0: the configuration file /usr/local/nginx-0.5.38/conf/nginx.conf syntax is ok
2018/08/24 10:32:51 [info] 9703#0: the configuration file /usr/local/nginx-0.5.38/conf/nginx.conf was tested successfully

-s 指定nginx的动作

nginx -s reload 平滑重启(重读配置文件),相当于kill -HUP cat /usr/local/nginx/logs/nginx.pid 重读配置文件,不重启服务(不会立即生效,等到进程关闭下次在链接的时候生效) nginx -s stop 强制终止,相当于kill -INT cat /usr/local/nginx/logs/nginx.pid nginx -s reopen 重新读取日志文件,相当于kill -USR1 cat /usr/local/nginx/logs/nginx.pid 如果不使用这个指令,我们还是没办法进行日志切割的,虽然我们把日志文件改了个名称,但是Linux是按照inode来区别文件的,不是按照文件名来区别文件的。所以我们需要告诉它,你记录的文件已经改变了,你需要重新加载一下日志文件

####-v/V显示nginx的版本编译版本和配置参数的

[root@WNginx01_7 nginx]# nginx -V
nginx version: nginx/0.5.38
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-23) (GCC) 
configure arguments: --user=web --group=web --prefix=/usr/local/nginx-0.5.38 --with-http_ssl_module --with-http_stub_status_module

Nginx的控制信号

kill -INT cat /usr/local/nginx/logs/nginx.pid 强制关闭进程,nginx -s stop

kill -HUP cat /usr/local/nginx/logs/nginx.pid 重读配置文件 nginx -s reload

kill -USR1 cat /usr/local/nginx/logs/nginx.pid 重新打开日志文件nginx -s reopen

Nginx的配置文件

cat /etc/nginx/nginx.conf
worker_processes  1;
#定义有多少个工作的子进程,可自行修改,太大无益,因为要争夺CPU,一般设置为核心总数(lscpu中CPU(S)可看)
events {
    worker_connections  1024;
	#一个worker允许同时最大产生多少个链接
}
http {			#Web功能的标签
    include       conf/mime.types;
	#设定mime类型,类型由conf/mime.types决定
    default_type  application/octet-stream;
    sendfile        on;
	#sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。
    keepalive_timeout  65;
    server {		#虚拟主机的标签
        listen       80;
		#侦听的端口
        server_name  localhost;
		#服务器的名称,别人可以通过这个来访问你的网站
        location / {
            root   html;
			#网站的根目录,如果是绝对路径,就是对于nginx服务器的家目录来说的
            index  index.html index.htm;
			#网站默认的查找首页,从左向右依次查找
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

基于IP地址的虚拟主机

在http标签里面添加上一对server标签
    server {
        listen 80;
        server_name 10.0.0.7;
		access_log logs/ip_access.log main;
        location / {
            root html/server_ip;
            index index.html
        }
    }
保存退出,检查语法
[root@WNginx01_7 nginx]# nginx  -c /usr/local/nginx/conf/nginx.conf -t 
2018/08/24 11:15:36 [info] 9888#0: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
2018/08/24 11:15:36 [info] 9888#0: the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully
平滑重启(重读配置文件)
[root@WNginx01_7 nginx]# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
创建虚拟主机的网站根目录,刚才在配置文件里面定义的
[root@WNginx01_7 nginx]# mkdir /usr/local/nginx/html/server_ip
进入到这个里面编辑网站的主页
[root@WNginx01_7 nginx]# cat /usr/local/nginx/html/server_ip/index.html
<html>
<center><h1>Welcome to 10.0.0.7 server test</h1></center>
</html>
#然后在浏览器上输入IP地址,发现内容正确显示,基于IP的虚拟主机配置完成

基于端口的虚拟主机(生产环境中可以通过这种方法给网站单独开个后台,增加安全性)

在http标签里面添加上一对server标签
    server {
        listen 8888;
        server_namelocalhost;
		access_log logs/8888_port_access.log main;
        location / {
            root html/port;
            index index.html
        }
    }
保存退出,检查语法
[root@WNginx01_7 nginx]# nginx  -c /usr/local/nginx/conf/nginx.conf -t 
2018/08/24 11:15:36 [info] 9888#0: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
2018/08/24 11:15:36 [info] 9888#0: the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully
平滑重启(重读配置文件)
[root@WNginx01_7 nginx]# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
创建虚拟主机的网站根目录,刚才在配置文件里面定义的
[root@WNginx01_7 nginx]# mkdir /usr/local/nginx/html/port
进入到这个里面编辑网站的主页
[root@WNginx01_7 nginx]# cat /usr/local/nginx/html/port/index.html
<html>
<center><h1>Welcome to 8888 server test</h1></center>
</html>
然后在浏览器上输入IP地址加端口号,发现内容正确显示,基于port的虚拟主机配置完成
![-c](media/15361471048983/15361480548388.jpg)
查看服务器侦听的端口
![-c](media/15361471048983/15361480949328.jpg)

1.5.3 基于域名的虚拟主机

在http标签里面添加上一对server标签
    server {
        listen 80;
        server_name www.sentinel.com;
		access_log logs/sentinel_access.log main;
        location / {
            root html/sentinel;
            index index.html
        }
    }
保存退出,检查语法
[root@WNginx01_7 nginx]# nginx  -c /usr/local/nginx/conf/nginx.conf -t 
2018/08/24 11:15:36 [info] 9888#0: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
2018/08/24 11:15:36 [info] 9888#0: the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully
平滑重启(重读配置文件)
[root@WNginx01_7 nginx]# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
创建虚拟主机的网站根目录,刚才在配置文件里面定义的
[root@WNginx01_7 nginx]# mkdir /usr/local/nginx/html/sentinel
进入到这个里面编辑网站的主页
[root@WNginx01_7 nginx]# cat /usr/local/nginx/html/sentinel/index.html
<html>
<center><h1>Welcome to www.sentinel.com server test</h1></center>
</html>
然后在本机的hosts文件里面写上www.sentinel.com和他的ip地址的对应关系,因为我们没有DNS服务器,虽然他是基于域名的,但是实际上还是通过ip地址来进行通信的。
[root@sentinel ~]# echo "10.0.0.7 www.sentinel.com" >>/etc/hosts
访问成功
![-c](media/15361471048983/15361481484667.jpg)

Nginx的变量:

  $request_length       请求长度(包括请求行,标题和请求正文)
  $request_method       请求的动作(get或者post)
  $request_time         请求时间(以毫秒为单位的请求处理时间(1.3.9,1.2.6); 从客户端读取第一个字节后经过的时间)
  $request_url          完整的原始请求URL(带参数)  
  $scheme               返回用的协议,是http还是https
  $remote_addr          客户端的地址
  $remote_port          client port
  $remote_user          基本认证的身份
  $server_addr          服务端的地址
  $server_port          server port
  $server_protocol      使用的http的版本“HTTP/1.0”, “HTTP/1.1”, or “HTTP/2.0”
  $status               回应状态
  $uri                  当前请求的url
  $body_bytes_sent      给你主体发送的字节
  $http_refrere         请求的上个页面来至于哪里
  $http_x_forwarded_for 代理服务器的IP地址
  $http_user_agent      浏览器的型号

Nginx的日志管理

在配置文件里面找到根nginx日志相关的配置文件
    #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;
作用域: http 服务器
指令log_format描述了日志条目的格式。除了格式中的一般变量之外,还可以使用仅在记录到日志中时存在的变量:
·$ body_bytes_sent,发送到客户端的字节数减去响应头,变量与模块Apache的mod_log_config的参数%B兼容(在版本0.3.10之前称为$ apache_bytes_sent)
·$ bytes_sent,传输到客户端的字节数
·$ connection,连接数
·$ msec,日志条目时精度为微秒的时间
·$ pipe,如果请求是流水线操作则为“p”
·$ request_length,请求正文的长度
·$ request_time,在几秒钟内处理请求的时间
·$ status,回答状态
·$ time_local,将本地时间转换为通用日志格式。
传输到客户端的标头从前缀“sent_http_”开始,例如$ sent_http_content_range。

Nginx的日志轮询。

要求每个server标签都有自己的日志文件,日志文件只保留7天,每个文件只保留一天的日志信息

#!/bin/bash
cd /usr/local/nginx/logs
DATE=`date +%Y%m%d`
for i in `ls *.log`
do
	echo $i |sed -r "s#(.*).log#mv $i 1-$DATE.log#g" | bash
	touch $i	
done
kill -USR1 `cat nginx.pid` && action "logs 轮询。sucess" /bin/true
echo "删除了这些日志"
find ./ -name "*.log" -type f -mtime +7 
find ./ -name "*.log" -type f -mtime +7 |xargs rm -f 

写到定时任务中

59 23 * * * /opt/scripts/log_lun.sh >>/var/log/Nginx_lunxu.logs

Nginx + PHP 通过NFS实现分离

nginx+php通过nfs共享达到分离

我们这边使用三台虚拟机

uname -a  
Linux sentinel.org.cn 2.6.32-696.el6.x86_64 
#1 SMP Tue Mar 21 19:29:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

ip地址规划

Nginx 10.0.0.7 PHP 10.0.0.200 NFS 10.0.0.41

Nginx采用的源码包下载:

#http://nginx.org/download/nginx-1.14.0.tar.gz

NFS采用的是yum安装,先搭建NFS服务器

yum -y install rpcbind nfs-utils
[root@NFS01_41 ~]# vim /etc/exports 
/data 10.0.0.0/24(rw,sync,all_squash,anonuid=888,anongid=888)
[root@NFS01_41 ~]# useradd -M -s /sbin/nologin -u 888 nfs
[root@NFS01_41 ~]# chown nfs:nfs /data/
[root@NFS01_41 ~]# exportfs -arv
exporting 10.0.0.0/24:/data
[root@NFS01_41 ~]# /etc/init.d/rpcbind start 
[root@NFS01_41 ~]# /etc/init.d/nfs start        
[root@NFS01_41 ~]# showmount -e 10.0.0.41    
Export list for 10.0.0.41:
/data 10.0.0.0/24

到此NFS服务配置成功

*然后搭建Nginx服务器。

采用nginx--yum安装*

cat >> /etc/yum.repos.d/nginx6.repo <<EOF
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/rhel/6/x86_64/
gpgcheck=0
enabled=1
EOF
yum -y install nginx nfs-utils rpcbind
[root@WNginx01_7 opt]# showmount -e 10.0.0.41
Export list for 10.0.0.41:
/data 10.0.0.0/24
[root@WNginx01_7 opt]# mkdir /var/html
[root@WNginx01_7 opt]# mount -t nfs 10.0.0.41:/data /var/html/
[root@WNginx01_7 opt]# df -Th 
Filesystem      Type   Size  Used Avail Use% Mounted on
/dev/sda3       ext4    19G  2.5G   16G  14% /
tmpfs           tmpfs  491M     0  491M   0% /dev/shm
/dev/sda1       ext4   190M   35M  146M  19% /boot
10.0.0.41:/data nfs     19G  2.5G   15G  15% /var/html
[root@WNginx01_7 opt]# cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/nginx.conf
[root@WNginx01_7 opt]# vim /etc/nginx/conf.d/nginx.conf

*然后安装php服务

源码安装php,我也不知道phpyum源为什么配置不上。正在研究(研究结果,同一个时间一个出网ip访问这个源的地址太多了,他们认为我们在恶意攻击,把我们的IP地址封了)*

[root@sentinel opt]# yum -y install gd gd-devel freetype libxml2 libxml2-devel nfs-utils rpcbind
[root@sentinel opt]# tar xf php-5.5.3.tar.bz2 
[root@sentinel opt]# cd php-5.5.3/
./configure 
--prefix=/usr/local/php-5.5.3 
 --enable-gd-native-ttf 
 --enable-dg-jis-conv 
 --with-mysql=mysqlnd 
 --enable-mysqlnd 
--enable-fpm 
make && make install
[root@sentinel php-5.5.3]# cp /opt/php-5.5.3/php.ini-development ./lib/php.ini
[root@sentinel php-5.5.3]# cp etc/php-fpm.conf.default etc/php-fpm.conf
[root@sentinel php-5.5.3]# vim etc/php-fpm.conf 
listen = 10.0.0.200:9000

[root@sentinel php-5.5.3]# mkdir /var/html
[root@sentinel php-5.5.3]# mount -t nfs 10.0.0.41:/data /var/html/

然后更给nginx的配置文件,更改location标签

location ~ .php$ {
    root           /var/html;
    fastcgi_pass   10.0.0.200:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /var/html/$fastcgi_script_name;
    include        fastcgi_params;
}

然后重启nginx服务

[root@WNginx01_7 opt]# nginx -s reload
[root@WNginx01_7 opt]# vim /var/html/test.php
<?php
phpinfo();

然后访问10.0.0.7/test.php

看到php测试页面,nginx和php分离成功

Centos7.5通过yum安装Nginx+php

安装Nginx前的准备工作

yum -y install pcre pcre-devel openssl openssl-devel

cat >> /etc/yum.repos.d/nginx.repo <<EOF
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/rhel/7/x86_64/
gpgcheck=0
enabled=1
EOF
yum clean all && yum makecache

开始yum安装Nginx

yum -y install nginx nginx-devel
查看安装之后相关的配置文件
[root@nginx01-41 ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/win-utf
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
/usr/lib/systemd/system/nginx.service		#启动的运行程序
/usr/sbin/nginx								#Nginx服务的主要命令
/usr/sbin/nginx-debug
/usr/share/nginx
/usr/share/nginx/html						#网站的默认根目录
/var/log/nginx								#nginx的日志文件
然后启动nginx
systemctl start nginx.service
然后访问ip地址,正常访问

安装PHP:

安装前准备

rpm -Uvh http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh http://mirror.webtatic.com/yum/el7/webtatic-release.rpm

开始安装php一系列软件包

yum -y install php71w php71w-cli php71w-common php71w-devel 
php71w-embedded php71w-gd php71w-mbstring php71w-pdo php71w-xml php71w-fpm 
php71w-mysqlnd php71w-opcache php71w-mcrypt php71w-pecl-memcached php71w-pecl-mongodb php71w-pecl-redis
安装完成之后更改Nginx的配置文件
vim /etc/php-fpm.d/www.conf
listen = 10.0.0.41:9000
listen.allowed_clients = 10.0.0.41
然后在Nginx的配置文件里面加上:
    server {
        listen 80;
        server_name localhost;      
        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
        location ~ .php$ {
          root           /usr/share/nginx/html;
          fastcgi_pass   10.0.0.41:9000;
          fastcgi_index  index.php;
          fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
          include        fastcgi_params;
        }
    }
然后在网站的根目录下面创建test的测试文件
[root@nginx01-41 ~]# cat /usr/share/nginx/html/test.php 
<?php
phpinfo();
?>

location 匹配规则

###匹配到符号

= 精确匹配,url必须和等号后面的一摸一样才能匹配成功 ~ 执行一个正则的匹配,区分大小写

~* 执行一个正则的匹配,不区分大小写

^~ 如果匹配到改选项,只匹配改选项,不匹配别的选项,一般用来匹配目录

###匹配过程

具体的匹配过程如下: 首先先检查使用前缀字符定义的location,选择最长匹配的项并记录下来。

如果找到了精确匹配的location,也就是使用了=修饰符的location,结束查找,使用它的配置。

然后按顺序查找使用正则定义的location,如果匹配则停止查找,使用它定义的配置。

如果没有匹配的正则location,则使用前面记录的最长匹配前缀字符location。

基于以上的匹配过程,我们可以得到以下两点启示:

使用正则定义的location在配置文件中出现的顺序很重要。因为找到第一个匹配的正则后,查找就停止了,后面定义的正则就是再匹配也没有机会了。

使用精确匹配可以提高查找的速度。例如经常请求/的话,可以使用=来定义location。

location = / {
    [ configuration A ]
}
location / {
    [ configuration B ]
}
location /documents/ {
    [ configuration C ]
}
location ^~ /images/ {
    [ configuration D ]
}
location ~* .(gif|jpg|jpeg)$ {
    [ configuration E ]
}

The “/” request will match configuration A, the “/index.html” request will match configuration B, the “/documents/document.html” request will match configuration C, the “/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E. 请求‘/’将返回配置A,请求‘/index.html’则返回配置B,请求‘/documents/document.html’返回配置C,请求“/images/1.gif”返回配置D,请求“/documents/

1.jpg”返回配置E,不返回配置C。请求“/images/1.gif”则返回D,不返回E

rewrith 重写模块

匹配优先级高于location模块。先匹配完rewirte_mould 在匹配location_mould模块。

if 判断:

if 空格(条件){

重写模式

}

条件: = 判断是否相等,用于字符串的比较

!= 两个字符串不相等为真

~ 用正则来匹配(正则区分大小写)

~* 正则不区分大小写

-f 检查文件是否存在,存在为真

!-f 文件不存在为真

-d 目录存在为真

!-d 目录不存在为真

-e 存在链接文件为真

!-e 不存在链接文件为真

-x 有执行权限为真

!-x 没有执行权限为真

条件:

set。 设置变量 return 返回状态码

break。 跳出rewrite

rewrite 重写

  rewirte 要重写的页面。 重写后的页面。

rewrite 重写的四种动作

last stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;

停止当前处理的ngx_http_rewrite_module的指令集,并开始搜索与更改后的url匹配的location。

break

stops processiong the current set of ngx_http_rewrite_modeule directives as with then break directive.
与break指令一样,停止处理当前的ngx_http_rewrite_module指令集。(直接跳出)

redirect

返回302临时重定向

permanent

返回301永久重定向

last 和 break的区别:

在server标签下: 是先执行rewrite模块的。

last和break没有什么区别,执行完成之后都会去接着匹配location,

在location标签下:

break 重写后,直接使用当前的资源,不在执行location里余下的语句,完成本次请求,地址栏的url不变(最长使用)

last 重写后,马上拿着重写后的地址发起一个新的请求,重新进入server块,重新匹配location,超过10次匹配不到报500错误,地址栏的url不变

实例:

将客户端访问的/image/下面的资源全部转到html下

rewrite ^/image/(.*)$ /html/$1 break;

支持后向引用。 $1代表前面第一个括号里面匹配的结果。

判断客户端如果使用的是chrome浏览器,我们就重写到chrome.html页面,如果访问的直接就是ie.html那个我们不重写

set 是设置变量用的,可以用来达到多条件判断时标志用:
if ($http_user_agent ~* chrome) {
  set $I 1;
}
if ($fastcgi_script_name = chrome.html) {
  set $I 0;
}
if ($I) {
  rewrite ^.*$ /chrome.html;
}

分析:

当我们使用chrome浏览器请求的不是chrome.html。html的时候,我们就匹配第一个,$I被赋值为1,然后开始向下匹配。发现$I=1的时候第三个if满足条件,然后执行里面的rewrite语句,把所有的资源都请求到了/chrome.html上面了。如果我们请求的是chrome.html页面,就会匹配第二个if,然后第三个if判断为假,就不执行rewrite动作了。所以我们拿两个浏览器同事请求一个不存在的页面的时候会发生下面情况 chrome浏览器

safari浏览器

Nginx的gzip_mould压缩模块

压缩输出数据流

Syntax:		gzip on | off;
Default:	gzip off;
Context:	http, server, location, if in location

是否开启gzip的压缩格式。

Syntax:		gzip_buffers number size;
Default:	gzip_buffers 32 4k|16 8k;
Context:	http, server, location

gzip的缓冲区,压缩在内存中缓冲多少块,每块多大,超过之后对硬盘输出,后面块的大小因该给磁盘的block块的大小保持一致。

Syntax:		gzip_comp_level level;
Default:	gzip_comp_level 1;
Context:	http, server, location

gzip的压缩级别,级别是1-9,数字越大压缩率越大,同时也更浪费cpu资源。建议使用6级别。

Syntax:		gzip_disable regex ...;
Default:	—
Context:	http, server, location

This directive appeared in version 0.6.23.

后面可以跟正则表达式,被这个正则匹配到的url不压缩

Syntax:		gzip_http_version 1.0 | 1.1;
Default:	gzip_http_version 1.1;
Context:	http, server, location

设置压缩响应所需的最低HTTP请求版本。

Syntax:		gzip_min_length length;
Default:	gzip_min_length 20;
Context:	http, server, location

这是gzip压缩的做小字节长度,低于这个字节长度的内容不压缩。

Syntax:	gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
Default:	gzip_proxied off;
Context:	http, server, location

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

Syntax:		gzip_types mime-type ...;
Default:	gzip_types text/html;
Context:	http, server, location

对那些类型的文件进行压缩,类型的书写格式可以从mime.types文件里面查看

Syntax:		gzip_vary on | off;
Default:	gzip_vary off;
Context:	http, server, location

是否传输gzip的压缩标志。

Nginx最长使用的配置

        gzip on;
        gzip_buffers 32 4k;
        gzip_comp_level 6;
        gzip_http_version 1.1;
        gzip_min_length 100;
        gzip_vary on;
        gzip_types text/css text/xml;

Nginx当作代理服务器proxy(动静分离)

客户端发出请求到代理服务器上,然后代理服务器帮他去后台请求资源,客户端认为代理服务器就是原始的web服务。

在Nginx配置文件里面的location 或者 if 标签里面添加

proxy_pass http://ip:port;原始服务器的地址,可以写多个
proxy_http_version 1.1|1.0; http的协议版本

搭建:

在31上安装Nginx服务

安装完成之后在配置文件里面加上:

location ~* .php {
     proxy_pass http://10.0.0.41;
}

然后在41上搭建nginx+php

配置文件里面加上:

vim /etc/nginx/nginx.conf
location ~ .(php|md)$ {
  root           /usr/share/nginx/html;
  fastcgi_pass   10.0.0.41:9000;
  fastcgi_index  index.php;
  fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
  include        fastcgi_params;
}

修改php的配置文件

vim /etc/php-fpm.d/www.conf
listen = 10.0.0.41:9000
listen.allowed_clients = 10.0.0.41

写一个测试文件,看看动静分离是否成功

[root@nginx01-41 ~]# cat /usr/share/nginx/html/test.php 
<?php
echo rand(1,100);
?>
<img src="iptables.png" />#路径写的是代理服务器上的路径

然后把这个图片来回的换位置,测试动静分离的静态文件是放在代理服务器上的。两台服务器的网站路径最好保持一致。

Nginx_upstream 负载均衡模块

Nginx的负载均衡 upstream_mould

在一个反向代理服务器上面配置多个proxy_pass 就是负载均衡

我们需要引进upstream模块来实现这个功能

实现方法:在upstream模块里面定义一个别名,然后在这个里面绑定多台服务器后段服务器的地址。然后在proxy里面写上这个别名即可

upstream只能写在http模块里面。

配置详解:

  upstream alias_name {
    #定义了一个所有负载均衡器的别名
  }
  里面的语句
  server address [parameters参数]
  parameters:
    weight=1;
      sets the weight of the server, by default, 1.  设置这个服务器每轮被接受请求多少次(默认是一个服务器每轮被请求1次)
    max_conns
      限制与代理服务器的最大连接数,默认是0,没有限制
    max_fails
      设置在规定时间内最大和服务器建立链接的次数,如果在规定时间内链接还没有建立成功,则认为建立失败,默认情况下这个次数被设置为1.
    fail_timeout=time
      不言而喻,这是设置失败链接次数的规定时间,默认10s
    backup
      将服务器标记为备份服务器,只有主服务器不可使用的时候,才会启用
    down
      将服务器设置为永久不可用

Nginx_auth_basic_module 简单认证

用"http basic authentication(简单的认证)"来限制用户的访问

一般的用法

location / { auth_basic string; auth_basic_user_file /etc/nginx/conf.d/htpasswd; }

Syntax:	    auth_basic string | off;
Default:	auth_basic off;
Context:	http, server, location, limit_except

使用基本的'http basic authentication'用户名和密码验证

Syntax:	auth_basic_user_file file;
Default:	—
Context:	http, server, location, limit_except

指定保存的用户和密码,格式如下

comment name1:password1

name2:password2:comment

name3:password3<!-- more -->文件名支持变量

我们也可以使用htpasswd工具来生成密码。用法如下

先安装yum -y install httpd-tools

查看htpasswd的用法

root@test ~# htpasswd --help Usage:

    htpasswd [-cimBdpsDv] [-C cost] passwordfile username
    htpasswd -b[cmBdpsDv] [-C cost] passwordfile username password
    htpasswd -n[imBdps] [-C cost] username
    htpasswd -nb[mBdps] [-C cost] username password

-c Create a new file.

//创建一个新的文件

-n Don't update file; display results on stdout.

-b Use the password from the command line rather than prompting for it.

//使用命令行中的密码,而不提示输入密码,非交互式创建密码

-i Read password from stdin without verification (for script usage).

//从stdin读取密码而不进行验证(用于脚本)

-m Force MD5 encryption of the password (default).

//使用md5加密(默认)

-B Force bcrypt encryption of the password (very secure).

//强制密码加密(非常安全)

-C Set the computing time used for the bcrypt algorithm

 (higher is more secure but slower, default: 5, valid: 4 to 31).

-d Force CRYPT encryption of the password (8 chars max, insecure).

-s Force SHA encryption of the password (insecure).

-p Do not encrypt the password (plaintext, insecure).

//不加密密码(明文,不安全)

-D Delete the specified user.

//删除指定用户

-v Verify password for the specified user.

On other systems than Windows and NetWare the '-p' flag will probably not work.

The SHA algorithm does not use a salt and is less secure than the MD5 algorithm.

用法实例

创建一个新的文件,并设置密码和用户,交互式

root@test ~# htpasswd -c /tmp/htpasswd linux New password:

Re-type new password:

Adding password for user linux

root@test ~# cat /tmp/htpasswd

linux:$apr1$3VhLd1HR$uSkhBgwIGYFDY5lWzZZsM0

添加一个新用户到配置文件中,非交互式创建密码

root@test ~# htpasswd -b /tmp/htpasswd baodian 321 Adding password for user baodian

root@test ~# cat /tmp/htpasswd

linux:$apr1$3VhLd1HR$uSkhBgwIGYFDY5lWzZZsM0

baodian:$apr1$ApIm66k6$CpqxwyqMUq.ZbcmMVELu10

删除一个指定的用户

root@test ~# htpasswd -D /tmp/htpasswd linux Deleting password for user linux

root@test ~# cat /tmp/htpasswd

baodian:$apr1$ApIm66k6$CpqxwyqMUq.ZbcmMVELu10 从指定的文件里面删除指定的用户