当前位置: 移动技术网 > 网络运营>网络>协议 > nginx介绍以及用法说明

nginx介绍以及用法说明

2020年07月17日  | 移动技术网网络运营  | 我要评论

nginx简介

(百度百科)Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。在连接高并发的情况下,Nginx是Apache服务不错的替代品,能够支持高达 50,000 个并发连接数的响应。

在web架构中的作用

nginx在web架构中最重要的有4个作用

  1. 反向代理
  2. HTTP服务器
  3. 负载均衡
  4. 正向代理

nginx安装

nginx安装参考:https://blog.csdn.net/haohao_ding/article/details/105765617

nginx配置文件


#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;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index   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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # 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;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index   index.htm;
    #    }
    #}


    # 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.htm;
    #    }
    #}

}

使用include拆分配置,生成环境中一般一个server一个配置文件方便管理

#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;

    #gzip  on;

    include /**/nginx/conf/extra/*.conf;

}

 

nginx.conf配置文件结构

  • main(全局设置)

user :主模块命令, 指定Nginx的worker进程运行用户以及用户组,默认由nobody账号运行。

worker_processes:指定Nginx要开启的进程数。

error log:用来定义全局错设日志文件的路径和日志名称。日志输出级别有debug,info,notice,warn,error,crit 可供选择,其中debug输出日志最为详细,面crit(严重)输出日志最少。默认是error。

pid:用来指定进程id的存储文件位置。

  • events设定nginx的工作模式及连接数上限

event:设定nginx的工作模式及连接数上限,其中参数use用来指定nginx的工作模式(这里是epoll,epoll是多路复用IO(I/O Multiplexing)中的一种方式),nginx支持的工作模式有select ,poll,kqueue,epoll,rtsig,/dev/poll。其中select和poll都是标准的工作模式,kqueue和epoll是高效的工作模式,对于linux系统,epoll是首选。

worker_connection:是设置nginx每个进程最大的连接数,默认是1024,所以nginx最大的连接数max_client=worker_processes * worker_connections。进程最大连接数受到系统最大打开文件数的限制,需要设置ulimit。

  • http 服务器相关属性
    • server(虚拟主机设置)

      • location(URL匹配特定位置后的设置)

    • upstream(上游服务器设置,主要为反向代理、负载均衡相关配置)

 

  • 虚拟主机

服务器主机分成一台台“虚拟”的主机,每台虚拟主机都可以是一个独立的网站,同一台主机上的虚拟主机之间是完全独立的。从网站访问者来看,每一台虚拟主机和一台独立的主机完全一样。配置文件中每一个server就是一台虚拟主机

案例一:

作为HTTP服务器,目前很多web项目采用前后端分离的模式,前端工程会独立部署在nginx服务器上,下面是最简单的部署形式。

server {
	#监听端口 8000
	listen 8000;
	#监听域名localhost;
	server_name localhost;
	location / {
		# 根目录路径
		root D:/work/auditView/dist;;
		# 默认跳转到页面
		index  index.htm;
	}
} 

上面的部署形式有些缺陷,只适合静态页面的部署,如果js中存在ajax请求,请求的ip,端口会被的写死,后端接口部署到其他环境需要修改ajax的请求不方便项目统一部署,所以一般的我们还会对ajax请求做反向代理。

 

案例二:

反向代理ajax请求

 

server {
	#监听端口 8000
	listen 8000;
	#监听域名localhost;
	server_name localhost;
	location / {
		# 根目录路径
		root D:/work/auditView/dist;;
		# 默认跳转到页面
		index  index.htm;
	}

	location /order {
		proxy_pass http://10.1.1.115:50000/;	
	}
	location /product{
		proxy_pass http://10.1.1.116:50010/;	
	}
}

但是随着项目的发展,http请求的访问量增加,后端服务做了集群后,需要前端负载均衡到不同后端实例。(这里不同于springcloud中zuul的负载均衡,但是可以使用到zuul服务的负载均衡上)

案例三:

负载均衡前端请求到不同的后端实例上

upstream order{
   # 负载均衡的servers
   server 10.1.1.100:50000;
   server 10.1.1.101:50000;
   server 10.1.1.102:50000;
   server 10.1.1.110:50000;
}
upstream product{
   # 负载均衡的servers
   server 10.1.1.200:50010;
   server 10.1.1.201:50010;
   server 10.1.1.202:50010;
   server 10.1.1.210:50010;
}

server {
	#监听端口 80
	listen 8000;
	#监听域名localhost;
	server_name localhost;
	location / {
		# 根目录路径
		root D:/work/auditView/dist;;
		# 默认跳转到页面
		index  index.htm;
	}

	location /order{
		proxy_pass http://www.lhsxpumps.com/_order/;	
	}

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

随着项目发展请求访问量的加大,后端实例节点也增加越多,此时nginx也达到上限,就需要nginx的集群了,这里不讨论(硬件上实现集群例如F5),我们可以使用keepalived实现,后面会简单介绍实现原理,目前由于一个域名可以绑定对个ip,所以目前使用更多的是使用域名绑定多个ip实现,效果优于keepalived。如果请求量更大就可以考虑硬件上集群F5了,当然这种也是成本最高的。

经过上面的几个简单例子我们具体看看nginx的规则:

首先是nginx的执行过程

nginx配置中最常用的配置,有些在上面的案例中已经用到了这里具体说明一下

upstream --- 用以配置负载的策略,nginx自带的有:轮询/权重/ip_hash。特殊需求可用第三方策略(使用较少)。

location:----用以匹配url信息结构,配足即进入对应逻辑块。是一套匹配逻辑的小型语法,核心是做url匹配。

rewrite:----用以修改url信息(ip+port部分无法改)的path部分,做重定向。与servlet类似,有页面重定向和内部重定向两类。

proxy_pass----用以转发命令。是实际的转发执行者。它可将流程转给upstream模块。

上面4个其中最为复杂的是location和rewrite

location的匹配规则如下:

说明几点:

1、通过url中【ip/域名+port】匹配server之后,携带后面path?params进入location逻辑

2、location匹配后,path = 匹配中的path1 + 剩余path2

 

3、root命令情况

location匹配后,path1=/static,path2=/a.html。

root方式是在目标html文件夹内,查找路径path1+path2=/static/a.html的文件。

4、alias命令情况

location匹配后,path1=/target,path2=/a.html。

alias方式是在目标html/static/文件夹内,查找路径path2= /a.html的文件。

5、root/alias 什么命令,目录是怎么配的

是声明,不是命令; 相当于java中:string rootPath = "/usr/local/html"; //就是根目录预置变量

rootPath = 初始值; ======/usr/local/nginx/html

nginx安装的时候,有一个目录就html目录(此目录就是用做初始值用)。

6、当在生产放文件,会是其它目录。不写root,会找错文件夹,定会错,root尽量都用绝对路径

 

rewrite的语法规则如下:

说明几点

1、

rewrite regex replacement [flag]; flag=【break/last/redirect/permanent

regex 是正则表达式

replacement 是替换值,新值

flag -- 是处理标志

例:http://rewrite.enjoy.com/aa.html --命中 /aa.html ,path=aa.html

本来应该在html/static文件夹下查找aa.html

 正则 ^/ 表示:总是匹配

若rewrite正则匹配命中,则修改为path = /a.html(若不命中呢,不执行)。

变成了在html/static文件夹下查找a.html

rewrite不命中,则rewrite更换path运作不会发生

 

2、

flag=【break/last/redirect/permanent/不写】含义。可以没有的。

/redirect/permanent,如果rewrite命中,发页面重定向

#http://rewrite.enjoy.com/b.html

会发生页面重定向

301/302重定向,对浏览器的记忆有区别

页面重定向,像servlet页面重定向一样,response返回。return;

#break/last 内部重定向,换path值

break标记,停止执行后续命令。for(){break}

last标记,会引发location重新匹配。for(){continue;}

ps : 不要轻易使用last标签

当有flag值的时候,rewrite层面的命令会中断。last会引发location重匹配

当没有flag值的时候,rewrite还会往下走,最后一个rewrite覆盖前面的。再引发location重匹配

 

nginx其他作用

1.nginx解决前端跨域问题

问题由来:浏览器拒绝执行其它域名下的ajax运作,这是浏览器的同源策略

如上图:chrome首次使用域名static.enjoy.com加载html页面------->然后在页面内由ajax方式向域名www.enjoy.com发起请求。

此时问题出现:chrome拒绝执行ajax请求得到的返回值。

 

此问题常见解决方案:

1、最常用的是,jsonp。此方案需要前后端共同协作来解决。

2、cors跨域,此方式非常优雅,是w3c组织制定的解决方案。为目前主流方案。方案流程如下图:

案例:

a、当chrome发现ajax请求的网址,与当前主域名不一致(跨域)时,会在请求header中追加值页面主域名值,即:origin = http://static.enjoy.com

 

b、nginx在接收到ajax请求时,会查看origin值,即请求我的网址是谁?

此处使用正则来校验,即:只要是enjoy.com下的网址,都允许访问我

返回信息时,nginx追加header值:access-control-allow-origin = static.enjoy.com(回答浏览器,static域名网址可以访问我)

c、chrome收到ajax返回值后,查看返回的header中access-control-allow-origin的值,发现其中的值是static.enjoy.com,正是当前的页面主域名。这是允许访问,于是执行ajax返回值内容。(ps:若此处access-control-allow-origin不存在,或者值不是static域名,chrome就拒绝执行返回值)

 

2.防盗链

目的:

1、让资源只能在我的页面内显示

2、不能单独来取或者下载

流程:

1、chrome以url1首次请求web服务器,得到html页面。

2、chrome再次发起url2资源请求,携带referers = url1。(注意,是url1,不是本次的url2)

3、nginx校验referers值,决定是否允许访问。

4、下面是nginx校验referers值的过程:

valid_referers:匹配域名白名单,如果不匹配,把内置变量$invalid_referers置为1,进入if块,返回404

3.缓存

expires命令:过期时间

4.压缩

过程:nginx压缩 ----》网络传输 ---》chrome解压(压缩和解压消耗cpu)

1、浏览器携带支持的解压方式

2、浏览器与nginx的交互

nginx配置

再来几个案例吧

案例4:

作为图片服务器,这个在我们之前的项目中都有使用过,适合图片量级较小的场景(10w张没什么问题,之前测试10w没出现任何问题)。

# 图片资源服务
server {
    listen       19001;
	charset gbk,utf-8; 
		
	location ~ .*\.(gif|jpg|jpeg|png)$ {
		root D:/root/uploadFiles/;
		expires -1; 
	}		
}

案例5:

提供目录浏览功能,这位也可作为图片资源服务器但是与上面不同的是它可以浏览整个目录,可以看到里面所有文件,所以作为图片资源服务器图片资源就都是公开的了,一般情况下使用上面的配置作为图片资源服务器。

# 开启目录浏览(文件服务器)
server {
    listen       9000;
	charset gbk,utf-8; 
		
	location /images/ {
		root  D:/root/uploadFiles/;
		autoindex on;
		autoindex_localtime on;
		autoindex_exact_size off;
	}
}
		

 

nginx高可用(keepalived实现)

a、nginx解决tomcat高可用的思路,是前面加一层负载服务nginx。这种做法,总会有一个前端负载层存在宕机可能,是死循环

 

b、keepalived来解决。

keepalived的思路,由 2台服务器软件虚拟出来一台 虚拟网关vip,

此vip由两台机器共同协商生成。当有一台机器宕机时,另一台机器一样能维持vip。这保证了,只要两台机器不同时宕机,vip就存在。

具体搭建可以自行百度,之前也说过生产环境一般不使用keepalived搭建集群,而是采用域名绑定多个ip的形式。

本文地址:https://blog.csdn.net/haohao_ding/article/details/107326613

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网