Nginx
Nginx目录
- conf
用来存放配置文件相关
- html
用来存放静态文件的默认目录 html、css等
- sbin
nginx的主程序
基本运行原理
Nginx配置文件
- worker_processes
worker_processes 1;默认为1,表示开启一个业务进程
- worker_connections
worker_connections 1024;单个业务进程可接受连接数
- include mime.types;
include mime.types; 引入http mime类型
- default_type application/octet-stream;
default_type application/octet-stream;如果mime类型没匹配上,默认使用二进制流的方式传输
- sendfile on;
sendfile on; 使用linux的sendfile(socket, file, len)高效网络传输,也就是数据0拷贝。
未开启sendfile开启sendfile
- server
虚拟主机配置
server {
listen 80; 监听端口号
server_name localhost; 主机名
location / { 匹配路径
root html; 文件根目录
index.html index.htm; 默认页名称
}
error_page 500 502 503 504 /50x.html; 报错编码对应页面
location = /50x.html {
root html;
}
}
AI 代码解读
虚拟主机
原本一个服务器只能对应一个站点,通过虚拟主机技术可以虚拟化成多个站点同时对外提供服务
servername匹配规则
需要注意servername匹配分先后顺序,写在前面的匹配上就不会继续往下匹配了。
完整匹配
我们可以在同一servername中匹配多个域名
serve_name void.test.com www1.test.com;
通配符匹配
server_name *test.com;
通配符结束匹配
server_name void.* ;
正则表达式
server_name ~^[0-9]+\.test\.com$ ;
Nginx反向代理
location / {
proxy_pass http://test;
}
AI 代码解读
基于反向代理的负载均衡
upstream test { server 服务地址:端口号; server 服务地址:端口号; ... }
AI 代码解读
- 负载均衡策略
- 轮询
默认情况下使用轮询方式,逐一转发,这种方式适用于无状态请求。
- weight(权重)
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
upstream test { server 服务地址:端口号 weight=10 down; server 服务地址:端口号 weight=1; server 服务地址:端口号 weight=2 backup; } down:表示当前的server暂时不参与负载 weight:默认为1.weight越大,负载的权重就越大。 backup: 其它所有的非backup机器down或者忙的时候,请求backup机器
AI 代码解读
- ip_hash
根据客户端的ip地址转发同一台服务器,可以保持会话。
- least_conn
最少连接访问
- url_hash
根据用户访问的URL定向转发请求(固定资源不在同一服务器上使用 ,不常使用,容易造成流量倾斜)
- fair
根据后端服务器响应时间转发请求
动静分离
- 配置反向代理
location / { proxy_pass http://服务地址:端口号; root html; index index.html index.htm; }
AI 代码解读
- 增加每一个location
location /css { root /usr/local/nginx/static; index index.html index.htm; } location /js { root /usr/local/nginx/static; index index.html index.htm; } location /img { root /usr/local/nginx/static; index index.html index.htm; }
AI 代码解读
- 使用一个location
使用正则 location前缀
/ 通用匹配,任何请求都会匹配到 =精准匹配,不是以指定模式开头 ~正则匹配,区分大小写 ~*正则匹配,不区分大小写 ^*非正则匹配,匹配以指定模式开头的location
AI 代码解读
location匹配顺序
- 多个正则location直接书写顺序匹配,成功后就不会继续往后面匹配
- 普通破(非正则)location会一直往下走,知道找到匹配度最高的(最大前缀匹配)
- 当普通location与正则location同时存在,如果正则匹配成功,则不会再执行普通匹配
- 所有类型location存在时,“=”匹配 > “^~”匹配 > 正则匹配 > 普通(最大前缀匹配)