4 Star 0 Fork 0

梦残 / 学习笔记

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
nginx.txt 44.10 KB
一键复制 编辑 原始数据 按行查看 历史
majie 提交于 2017-12-29 13:42 . 添加nginx下载文件方法
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
基于nginx的中间件架构
一丶学习环境
CPU>=2core 内存>=256M
操作系统
centos>=7.0 64位
四项确认:
1.系统网络
2.yum可用
3.关闭iptables
4.停用selinux
getenforce 查看状态
setenforce 0 关闭
两项安装
yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake //系统基本库
yum -y install wget httpd-tools vim //安装vim工具
调试环境确认:
一次初始化
cd /opt
mkdir app download logs work backup
二丶nginx简述
是一个开源且高性能,可靠的http中间件,代理服务
1.丶常见的HTTP服务
HTTPD
IIS
GWS-Google
2.为什么选择nginx
原因1:epoll
1.IO多路复用epoll
什么是IO复用:用一个socket
主动上报,提高效率
多个描述的IO操作都在一个线程内并发交替的顺序完成,这就叫IO多路复用,这里的复用指的是复用同一个线程
2.什么是epoll
IO多路复用的实现方式select,poll,epoll
select的缺点:
1)能够见识文件描述符的数量存在最大限制(1024个)
2)线性扫描效率低下
epoll模型
1)每当FD就绪,采用系统的回调函数之间将fd放入,效率更高
2)最大连接无限制
原因2:轻量级
功能模块少
代码模块化
原因3:CPU亲和(affinity)
1.什么是CPU亲和
是一种把CPU核心和nginx工作进程绑定方式,把每个worker进程固定在一个cpu上执行,减少切换cpu的cache miss,获得更好的性能
原因4:sendfile(不经过用户空间)
过程 File --> buffer cache ---->kernel space ---->buffer cache --->socket
三丶nginx快速搭建与基础参数使用
mainline version -- 开发版本
stable verison --稳定版本
legacy version --历史版本
1.安装步骤:
vim /etc/yum.repos.d/nginx.repo
复制
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
yum list | grep nginx 查看nginx版本
yum install nginx 安装
nginx -v 测试安装成功
2.基础参数使用
systemctl start nginx.service 启动
systemctl enable nginx.service 开机启动
关闭防火墙
systemctl stop firewalld.service
禁止开机启动防火墙
systemctl disable firewalld.service
查看防火墙状态
filewall-cmd --state
安装目录
rpm -ql nginx 查看安装目录
安装目录详解
/etc/logrotate.d/nginx 配置文件 nginx日志轮转,用于logrotate服务日志的切割
/etc/nginx 目录,配置文件 nginx主配置文件
/etc/nginx/nginx.conf
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf 默认service加载配置文件
/etc/nginx/fastcgi_params cgi配置相关,fastcgi配置
/etc/nginx/uwsgi_params
/etc/nginx/scgi_params
/etc/nginx/mime.types 配置http协议的Content-Type与扩展名对应关系
/usr/lib/systemd/system/nginx-debug.service 用于配置出系统守护进程管理器管理方式
/usr/lib/systemd/system/nginx.service
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
/usr/lib64/nginx/modules nginx模块目录
/etc/nginx/modules
/usr/sbin/nginx nginx服务的启动管理器的终端命令
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.12.0 nginx的手册和帮助文件
/usr/share/doc/nginx-1.12.0/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/var/cache/nginx nginx的缓冲目录
/var/log/nginx nginx的日志目录
编译参数
nginx -v 查看版本号
nginx -V 查看模块
设定nginx进程启动的用户和组用户
--user=nginx
--group=nginx
默认nginx 处于安全考虑
--with-cc-opt=parametes 设置为的参数将被添加到CFLAGS变量
--with-Id-opt-parametes 设置附加的参数,链接系统库
nginx配置文件
vim /etc/nginx/nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn; //配置错误日志 路径和级别
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main; //access_log 路径 main格式
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf; //默认配置文件
}
vim /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/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 /usr/share/nginx/html; //50x的错误页面
}
# 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;
#}
}
nginx基本语法
1.http请求
request
客户端 -------------------------->服务端
<----------------------------
response
request - 包含请求行,请求头部,请求数据
response - 包含状态行,消息报头,相应正文
curl -v www.baidu.com 查看每次请求的内容
curl -v www.baidu.com >/dev/null 重定向到linux的一个空设备上
浏览器用F12
2.nginx的日志类型
包括 error.log.access_log
实现:
log_format
只能配置在http这个模块
3.nginx变量
http请求变量 -
request的参数
arg_PARAMETER,
http_HEADER,
sent_http_HEADER. sent跟前面的区别,是服务端返回给客户的response的header
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
$request 的请求行
$status 返回状态
$http_referer 上一级页面地址
内置变量 - nginx内置的
自定义变量 - 自己定义
四.nginx官方模块
nginx官方模块
nginx -V 查看模块
--with-http_stub_status_module nginx的客户端状态,监控nginx的信息
http_stub_status_module配置语法:
Syntax: stub_status;
Default: -- 默认没有配置
Context:server,location
location /mystatus {
stub_status;
}
检查语法是否正确
nginx -tc /etc/nginx/nginx.conf
重载服务
nginx -s reload -c /etc/nginx/nginx.conf
--with-hhtp_random_index_module 目录中选择一个随机主页(很少用)
配置语法:
Syntax: random_index on|off;
Default: random_index off
Context:location
--with-http_sub_module http内容替换
语法1:
Syntax: sub_filter string replacement;
string表示需要替换的内容 replacement要替换的内容
Default: --
Context:http,server,location
如果加在http下面,可以对多个server进行字符串的替换
示例:
location /{
root /opt/app/coe; //路径
index index.html //网页
sub_filter '<a>你要替换的</a>' '替换以后的';
}
//上面只会替换第一个
//添加sub_filter_once off 开启替换所有
systemctl reload nginx //重启
语法2:
服务端和客户端交互内容是否有更新,如果有返回最新,如果没直接返回,主要用于缓存的场景
Syntax: sub_filter_last_modified on|off;
Default: sub_filter_last_modified off;
Context:http,server,location
语法3:
匹配所有html的代码的第一个还是匹配所有字符串
Syntax: sub_filter_once on|off;
Default: sub_filter_once on; //匹配第一个
Context:http,server,location
nginx的请求限制
连接频率限制 -limit_conn_moudule
请求频率限制 -limit_req_moudule
HTTP协议版本 连接关系
HTTP1.0 TCP不能被复用
1.1 顺序性TCP复用
2.0 多路复用TCP复用
HTTP协议的连接与请求
HTTP请求建立在一次TCP连接的基础之上
一次TCP请求至少产生一次HTTP请求
连接限制
Syntax: limit_conn_zone key zone=name:size;
Default:--
Context:http
limit_conn_zone 存储连接的空间
以别的内置变量作为key就写在key里面
size是申请空间的大小
Syntax: limit_conn_zone number;
Default:--
Context:http,server,location
这里直接调用上面的zone
请求限制:
Syntax: limit_req_zone key zone=name:size rate=rate
Default:--
Context:http
rate是速率 通常以s为单位
Syntax: limit_req zone=name [burst=number] [nodelay]
Default:--
Context:http,server,location
burst
nodelay
示例:
http里配置
limit_conn_zone $binary_remote_addr zone=conn_zone:1m;
limit_req_zone $binary_romote_addr zone=req_zone:1m rate=1r/s; //同一个请求
location / {
root /opt/app/code;
#limit_conn conn_zone 1;
#limit_req zone=req_zone burst=3 nodelay;
index index.html;
}
nginx的访问控制:
基于IP的访问控制 - http_acess_module
基于用户的信任登录 - http_auth_basic_module
http_acess_module的配置语法:
Syntax: allow address | CIDR(网段) | unix: |all(所有);
Default: --
Context:http,server,location,limit_except
相反deny是拒绝
示例:
//自己的ip不可以访问,别人的ip都可以访问
location ~(访问路径做模式匹配) ^/admin.html {
root /opt/app/code;
deny 自己的ip;
allow all;
indxe admin.html;
}
局限性:
如果有代理的话限制的是代理,而不是真正的地址
方法1:
http_x_forwarded_for(http头信息规定要带的,会记录整个ip通过代理的过程)
http_x_forwarded_for = Client IP,Proxy(1) IP,Proxy(2) IP...
存在问题,只是协议要求.存在协议修改的可能性
方法2:
结合geo模块作
方法3:
通过http自定义变量传递
在http头请求规定一个变量,一级一级的传递到后端.
http_auth_basic_module
Syntax: auth_basic string | off
Default: auth_basic off;
Context:http,server,location,limit_except
Syntax: auth_basic_user_file file; //文件路径.存储用户名信息
Default: --
Context:http,server,location,limit_except
# comment
name1:password1
name2:password2:comment
yum -y install httpd-tools 安装密码处理工具
示例:
生成密码文件 htpasswd -c ./auth_conf(指定路径) majie(用户名)
查看
more /auth_conf
location ~(访路径做模式匹配) ^/admin.html {
root /opt/app/code;
auth_basic "Auth acess test!input your password"
auth_basic_user_file /etc/nginx/auth_conf
indxe admin.html;
}
局限性:
1.用户信息依赖文件方式,效率低下
2.操作管理机械,效率低下
解决方案:
1.nginx + lua 搞笑验证
2.nginx + LDAP 打通,利用nginx-auth-ldap
进阶:
一丶静态资源WEB服务
1.静态资源类型
非服务器动态运行形成的文件
类型 种类
浏览器端渲染 html.css.js
图片 JPEG,GIF,PNG
视频 FLV,MPEG
文件 TXT,等任意下载文件
2.静态资源服务场景-CDN
文件读取:
Syntax: sendfile on | off;
Default: sendfile off;
Context:http,server,location,if in location
引读:--with-file-aio 异步文件读取 不完善
tcp_nopush //将多个包整合一次性发送,大文件打开
Syntax: tcp_nopush on | off
Default: tcp_nopush off;
Context:http,server,location
作用:sendfile开启的情况下,提高网络包的传输效率
tcp_nodelay (实时性要求较高时候)
Syntax: tcp_nodelay on|off
Default: tcp_nodelay on;
Context:http,server,location
作用:keeplive连接下,提高网络包的传输实时性
3.压缩:
Syntax: gzip on | off
Default:gzip off;
Context:http,server,location,if in location
作用:压缩传输
压缩比:
Syntax: gzip_comp_level level;
Default: gzip_comp_level 1;
Context:http,server,location
压缩版本:
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context:http,server,location
4.扩展nginx压缩模块
http_gzip_static_module -预读gzip功能
http_gunzip_module --应用支持gunzip的压缩方式(很少用到,主要用于不能gzip的浏览器)
示例:
server {
listern 80;
server_name 192.168.31.109;
sendfile on; //开启文件读取
#charset koi8-r;
access_log /var/...
location ~ .*\.(jpg|gif|png)$ { //图片格式结尾
gzip on; //开启压缩
gzip_http_version 1.1; //http协议版本号
gzip_comp_level 2; //压缩率
gzip_types .... //压缩的类型
root /opt/app/code/images;
}
location ~ .*\.(txt|xml)$ { //txt|xml文件
gzip on; //开启压缩
gzip_http_version 1.1; //http协议版本号
gzip_comp_level 2; //压缩率
gzip_types .... //压缩的类型
root /opt/app/code/doc
}
location ~ ^/dowmload {
gzip_static on; //预读gzip
tcp_nopush on; //一次性提交
root /opt/app/code
}
}
对文本的压缩最好
手动gzip
gzip ./test.img
二.浏览器缓存
1.HTTP协议定义的缓存机制(如:Expires;Cache-control等)
2.浏览器无缓存
浏览器请求--->无缓存--->请求web服务器--->请求成功,协商--->呈现
3.客户端有缓存
浏览器请求 --->有缓存 --->校验过期 ---->呈现
4.检验过期机制
1.校验是否过期:Expires,Cache-control(max-age)
检查周期是否在本地缓存周期内,不在进行2
2.协议中Etag头信息校验 Etag 一串特殊的字符串
3. Last-Modified头信息校验 last-modified后面跟了时间
5.expires
添加Cache-Controll,Expires头
Syntax: expires[modified] time;
expires epoch | max | off; (用的少)
Default: expires off;
Context:http,server,location,if in location
//访问html/htm
location ~ .*\.(html|htm)$ {
expires 24h; //缓存24小时
root /opt/app/code;
}
出现304是服务端没有更新
三丶跨域访问
为什么禁止浏览器跨域访问;
不安全,容器出现CSRF攻击(跨站攻击)
nginx操作
Syntax: add_header name value [always];
Default:--
Context:http,server,location
Access_Controller-Allow-Origin
//设置允许跨域访问
location ~ .*\.(html|htm)$ {
add_header Access_Controller-Allow-Origin 192.168.31.109;
add_header Access_Controller-Allow-Method GET,POST,PUT,DELETE,OPTIONS;
root /opt/app/code;
}
四丶防盗链
1.目的:防止资源被盗用
2.防盗链设置思路
首要方式:区别哪些请求是非正常的用户请求
3.基于http_refer防盗链配置模块
Syntax: valid_referes none | blockd | server_names | string ...;
Default: --
Context:server,location
http_refer日志的一个变量信息
配置:
location ~ ....{
valid_referes none blocked 192.168.31.109;
if($invalid_referer){
return 403; //invalid_referer为1,进行跳转
}
root /opt/app/code/images;
}
none 代表没有referer
blocked 代表有referer但是被防火墙或者是代理给去除了
string或者正在表达式 用来匹配referer
nginx会通过查看referer字段和valid_referers后面的referer列表进行匹配,如果匹配到了就invalid_referer字段值为0 否则设置该值为1
curl -I www.baidu.com //发送不带refere信息,只发送请求头
curl -e "www.baidu.com" -I "www.baidu.com" //e带refere信息,但是上面规定是要求ip
五丶代理服务
1.代理--代为办理(代理理财,代理收货等等)
2.代理
请求 请求
客户端--------->代理----------->服务端
3.代理服务
HTTP
-------------> -------->http server
ICMP\POP\IMAP
客户端 --------------> nginx -------->mail server
HTTPS
---------------> --------> http server
RTMP
------=-------> --------> media server
4.正向代理 |
|
客户端 <----------> 代理 ------------->服务端
|
|
5.反向代理
|
|
客户端 ----------> 代理 <------------->服务端
|
|
6.代理区别
区别在于代理的对象不一样
正向代理代理的对象是客户端
反向代理代理的对象是服务端
7.配置语法
Syntax: proxy_pass URL;
Default: --
Context:location
支持http,https,socket
socket的
http://unix:/tmp/backend.socket:/uri/;
反向代理示例:
locaction ~ /test_proxy.html$ {
proxy_pass http://127.0.0.1:8080
}
//检查配置文件语法
nginx -t -c /etc/nginx/nginx.conf
正向代理示例:
location / {
//判断地址是不是这个地址,不是就跳到403
if( $http_x_forwarded_for !~* "116\.62\.103\.228"){
retrun 403;
}
root /opt/app/code;
index index.html;
}
//把所有请求都代理到这个请求
resolver 8.8.8.8; google 的 DNSserver
location / {
proxy_pass http://$http_host$request_uri;
}
8.缓冲区:
Syntax: proxy_buffering on | off;
Default:proxy_buffering on;
Context:http,server,location
扩展:proxy_buffer_size,proxy_buffers,proxy_busy_buffers_size
跳转重定向:
Syntax: proxy_redirect default;
proxy_redirect off;
proxy_redirect redirect replacement;
Default:proxy_redirect default;
Context:http,server,location
头信息:
Syntax: proxy_set_header field value;
Default:proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
Context:http,server,location
扩展:proxy_hide_header,proxy_set_body //隐藏头信息和设置body
超时:
Syntax: proxy_connect_timeout time;
Default: proxy_connect_timeout 60s;
Context:http,server,location
扩展:proxy_read_timeout,proxy_send_timeout //读\写超时
示例:
//公用的放到一个文件
location / {
proxy_pass http://192.168.31.109:8080;
proxy_redirect default;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffer_size 32k; //缓冲区大小
proxy_buffering on; //开启缓冲
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k; //
proxy_max_temp_file_size 256k; //最大临时文件大小
}
9.负载均衡:
---------> 服务1
1.客户 -------> nginx ---------> 服务2
---------> 服务3
2.GSLB(调度节点)
全局的负载均衡.以国家或者省委单位
3.SLB(常用) nginx是典型的SLB
4.分为四层负载均衡和七层负载均衡
四层:直接转发
七层:nginx典型的7层,可以处理
5.nginx负载均衡
upstream server
proxy_pass ---------> 服务1
客户 -------> nginx ---------> 服务2
---------> 服务3
6.配置语法
Syntax: upstream name {... }
Default: --
Context:http //只能在http层
示例:
http{
upstream cat { //代理三个端口
server 192.168.31.109:8081;
server 192.168.31.109:8082;
server 192.168.31.109:8083;
}
server{
listen 80;
location / {
proxy_pass http://baidu.com;
include proxy_params;
}
}
}
11.upstream举例
upstream backend {
server backend1.example.com weight=5; //权重
server backend2.example.com:8080; //端口
server unix:/tmp/backend3;
server backup1.example.com:808 backup;
server backup2.example.com:808 backup;
}
12.后端服务器在负载均衡调度中的状态
down 当前的server暂时不参与负载均衡
backup 预留的备份服务器
max_fails 允许请求的失败次数
fail_timeout 经过max_fails失败后,服务暂停的时间
max_conns 限制最大的接收的连接数
示例:
upstream test {
server 192.168.0.109:8081 down;
server 192.168.31.109:8082 backup;
server 192.168.31.109:8083 max_fails=1 fails_timeout=10s;
}
location / {
proxy_pass http://test;
include proxy_params;
}
13.调度算法:
轮询 按照时间顺序逐一分配到不同的后端服务器
加权轮询 weight值越大,分配到的访问几率就越高
ip_hash 每个请求按照访问ip的hash结果分配,这样来着同一ip的固定访问到一个后端
least_conn 最少连接数,哪个机器连接数少就分发
url_hash 按照访问的url的hash结果进行分配
hash关键数值 hash自定义的key
ip_hash示例:
upstream test {
ip_hash;
server 192.168.0.109:8081;
server 192.168.31.109:8082;
server 192.168.31.109:8083;
}
url_hash
Syntax: hash key [consisten];
Default:--
Context:upstream
1.7.2版本以后
示例
upstream test {
hash $request_url;
server 192.168.0.109:8081 down;
server 192.168.31.109:8082 backup;
server 192.168.31.109:8083 max_fails=1 fails_timeout=10s;
}
//针对某个值
14丶缓存类型
客户端第一次请求ginx,没有缓存就访问服务器,缓存到nginx,返回页面
第二次反问,nginx有缓存就直接返回
proxy_cache配置语法:
Syntax: proxy_cache_path path [levels=levels]
[use_temp_path=on|off] keys_zone=name:size
[inactive=time] [max_zize=size] ....
Default: --
Context:http
Syntax: proxy_cache zone on|off;
Default:proxy_cache off;
Context:http,server,location
缓存过期周期
Syntax: proxy_cache_valid [code...] time;
Default:--
Context:http,server,location
缓存的维度:
Syntax: proxy_cache_key string;
Default:proxy_cache_key $scheme$proxy_host$request_uri;
Context:http,server,location
示例:
proxy_cache_path /opt/app/cache levels=1:2 keys_zone=test_cache:10m
max_size=10g inactive=60 use_tem_path=off;
要匹配置在upstream下一级
inactive=60表示60分钟没有被访问过得就会被清楚(空间满的情况下)
location / {
proxy_cache test;
proxy_pass http://imooc;
proxy_cache_valid 200 304 12h; //200 304 的缓存12小时
proxy_cache_valid any 10m; //其他任何10分钟
proxy_cache_key $host$uri$is_args$args;
add_header Nginx-Cache "$upstream_cache_status"; //添加头信息,告诉客户端是否命中
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
//单台服务器出现500 502 503 504时候访问下一台服务器
include proxy_params;
}
如何清理指定缓存
1.rm -fr 缓存目录内容
2.第三方模块ngx_cache_purge
如何让页面不缓存
Syntax: proxy_no_cache string ...;
Default:--
Context:http,server,location
示例:
server{
//设置不缓存的页面
if($request_uri ~ ^/(url3|login|register|password\/reset)){
set $cookie_nocache 1;
}
location / {
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pragma $http_authorization;
}
}
大文件分片请求
Syntax: slice size;
Default: slice 0
Context:http,server,location
大文件分片请求
优势:每个子请求收到的数据都会形成一个独立的文件,一个请求断了,其他请求不收影响,基于原来的请求继续请求就好了
缺点:当文件很大或者slice很小的时候,可能会导致文件描述耗尽等情况.
六丶动静分离
示例:
upstream java_api {
server 192.168.0.109:8080;
}
server {
location ~ \.jsp$ {
proxy_pass http://java_api;
index index.html;
}
location ~ \.(jpg|png|gif)$ {
expires 1h;
gzip on;
}
}
1.动静分离:
通过中间件将动态请求和静态请求分离.
原因:分离资源,减少不必要的请求消耗,减少请求延时.
动态资源:
请求----->中间件----->程序框架----->程序逻辑 数据资源
<----- <------ <-----
静态:
请求------>中间件
<------
2.rewrite规则:
实现url重写以及url重定向
场景:
1.url访问跳转,支持开发设计
页面跳转,兼容性支持,展示效果等.
2.SEO优化
3.维护
后台维护,流量转发
4.安全
实现伪静态,将真实的页面进行伪装
语法:
Syntax: rewrite regex replacemeng [flag];
Default: --
Context:server,location,if
示例:
rewrite ^(.*)$ /pages/maintain.html break; //所有的请求都重定向到/pages/maintain.html页面
3.正则表达式
() 用于匹配括号之间的内容,通过$1,$2调用
示例:
if($http_user_agent ~ MISE){ //httpusergent是否包含 MISE
rewrite ^(.*)$ /mise/$1 break; //$1代表()的内容
}
终端测试命令pcretest
4.flag
标志nginx的rewrite规则对应的类型
常见类型:
last 停止rewrit检查
break 同上
redirect 返回302临时重定向,地址栏会显示跳转后的地址
permanent 返回301永久重定向,地址栏会显示跳转后的地址
示例:
root /opt/code;
location ~ ^/break {
rewrite ^/break /test/ break;
}
location ~ ^/last {
rewrite ^/last /test/ last;
}
location /test/ {
default_type application/json;
retrun 200 '{"status":"success"}'
}
分析:
break会先去匹配root目录下的/test,没有直接返回404
last也是会去匹配root的/test,会新建一次请求,请求服务端,域名/test.所以会请求到数据
5. 重定向redirect 和 permanent
location ~ ^/test {
# rewrite ^/test http://baidu.com/ permanent; //永久重定向
rewrite ^/test http://baidu.com/ redirect; //临时重定向
}
location / {
rewrite ^/course-(\d+)-(\d+)-(\d+)\.html$ /course/$1/$2/course_$3.html break;
}
//判断浏览器是否是Chrome
if($http_user_agent ~* Chrome) {
rewrite ......;
}
//判断文件名是否存在
if(!-f $request_filename) {
rewrite .......;
}
6.rewrite规则优先级
server
location
最后location的rewrite
优雅的书写规则
server {
listen 80;
server_name www.nginx.org nginx.org;
if($http_host = nginx.org){
rewrite (.*) http://www.nginx.org$1;
}
}
七丶 nginx的高级模块
1.secure_link_module模块 安全连接模块
1.限制并允许检查请求的连接的真是性以及保护资源免遭未经授权的访问
对于请求连接的真实性验证
保护我们的资源未被允许的访问
2.限制连接生效周期
下载连接有一定的时间周期,防止被一直下载
语法:
Syntax: secure_link expression;
Default:--
Context:http,server,location
Syntax:secure_link_md5 expression;
Default:--
Context:http,server,location
3.secure_link_module验证图示
点击下载按钮
------------------------------------> 生成下载地址
告诉客户端
客户端 <------------------------------------ 服务端
/dowmload?md5=xxxxxxxxxx&expires=过期时间戳
-----------------------------------------> 校验
下载资源
<-------------------------------------
校验图示
/dowmload?md5=xxxxxxxxxx&expires=过期时间戳
xxxxxx加密验证 验证在nginx,验证通过以后再验证时间戳
expires过期时间戳校验 验证在nginx
示例:
locaiton / {
secure_link $arg_md5,$arg_expires;
secure_link_md5 "$secure_link_expires$uri test"; //test自定义的加密串
if($secure_link = ""){
retrun 403;
}
if($secure_link = "0"){
retrun 410;
}
}
2.geoip_module模块
基于ip地址匹配MaxMind GeoIP二进制文件,读取ip所在地域的信息
安装:
yum intall nginx-module-geoip
http_geoip_module使用场景
1.区别国内外做http访问规则
2.区别国内城市地域作为http访问规则
示例:
下载ip地域文件
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
解压gunzip
加载模块nginx.conf
load_module "modules/ngx_http_geoip_module.so";
load_module "modules/ngx_stream_module.so";
配置
geoip_country /etc/nginx/geoip/GeoIP.dat; //定义路径
geoip_city /etc/nginx/geoip/GeoLiteCity.dat;
server {
location / {
if ($geoip_contry_code != CN){ //不是中国
retrun 403;
}
root /usr...;
index ...;
}
location /myip {
default_type text/plain;
return 200 "$remote_addr $geoip_country_name $geoip_country_code $geoip_city";
}
}
八丶HTTPS服务
讲解HTTPS协议原理,优劣势
1.为什么需要https
原因:HTTP不安全
1.传输数据被中间人盗用,信息泄露
2.数据内容被劫持,篡改
2.https协议实现
对传输内容进行加密以及身份验证
3.对称加密和非对称加密
4.HTTPS加密协议原理
1.发送SSL连接 (保管唯一私钥)
客户端 ----------------------------------------------->服务端
2.发送公钥
<-----------------------------------------------
3.发送对称密码(发送对称密码利用公钥加密)
------------------------------------------------>
4.利用对称密钥传输数据
<------------------------------------------------>
CA签名证书
客户端对数字证书进行CA校验
1.如果校验成功利用公钥加密
2.失败停止会话
生成秘钥和CA签名证书:
1.前提:openssl version //没有就安装ssl
nginx -V 查看有没有--with-http_ssl_module
2.生成key密钥
1.nginx目录下 mkdir ssl_key
2.openssl genrsa -idea -out majie.key 1024
3.生成证书签名请求文件(csr文件)
3.openssl req -new -key majie.key -out majie.csr
4.生成证书签名文件(CA文件)
4.openssl x509 -req -days 3650 -in majie.csr -singkey majie.key -out majie.crt
3650不写默认一个月过期
5.https服务优化
1.激活keeplive长连接
2.设置ssl session缓存
设置:
server{
keepalive_timeout 100;
ssl on;
ssl_session_cache shard:SSL:10m;
ssl_session_timeout 10m;
}
使用pfx生成ssl证书
生成证书crt可key
openssl pkcs12 -in /usr/local/nginx/ssl/SHA256withRSA_app.lichijituan.cn.pfx -clcerts -nokeys -nokeys -out /usr/local/nginx/ssl/SHA256withRSA_app.lichijituan.cn.crt
openssl pkcs12 -in /usr/local/nginx/ssl/SHA256withRSA_app.lichijituan.cn.pfx -nocerts -nodes -out /usr/local/nginx/ssl/SHA256withRSA_app.lichijituan.cn.rsa
验证证书正确性
openssl s_server -www -accept 443 -cert /usr/local/nginx/ssl/SHA256withRSA_app.lichijituan.cn.crt -key /usr/local/nginx/ssl/SHA256withRSA_app.lichijituan.cn.rsa
九丶nginx 与 lua 开发
lua及基础语法
nginx与lua环境
场景:用nginx 结合lua实现代码的灰度发布
1.LUA
是一个简洁清凉可扩展的脚本语言
2.nginx + lua优势
充分的结合nginx的并发出来epoll优势和lua的轻量实现简单的功能且高并发的场景
3.基础语法
1.安装
yum install lua
交互式:
lua
print("hello world")
脚本:
#! /usr/bin/lua
print("hello world")
./test.lua
2.lua的基础语法
注释: -- 行注释
--[[
块注释
--]]
3.变量
a='alo\n123"'
a="alo\n123\""
a=[[alo
123"]]
只有double型,没有其他的变量类型
布尔类型只有nil和false
注意:
false表示false,数字0," 空字符串 ('\0') 都是true
lua中的变量如果没有特殊说明都是全部变量.除非加local才是局部变量
4.while循环语句
sum = 0
num = 1
while num <= 100 do
sum = sum + num
num = num + 1
end
print("sum = ",sum)
lua不支持++或者是+=这样的操作
5.for循环
sum = 0
for i = 1,100 do
sum = sum + i
end
6.if-else判断语句
if age == 40 and sex == "Male" then
print("大于40 男人")
elseif age > 60 and sex ~= "Female" then
print
else
local age = io.read() --从屏幕终端读取深入信息
print("your age is " ..age)
end
~= 不等于
".." 字符串的拼接
4.nginx + lua 环境(http://www.imooc.com/article/19597)
1.LuaJIT lua的解释器,比lua解释器更加高效
2.ngx_devel_kit和lua_nginx_module
3.重新编译nginx
wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
解压
make
make install
导入环境变量
export LUAJIT_LIB=/usr/local/LuaJIT/lib
export LUAJIT_INC=/usr/local/LuaJIT/include/luajit-2.0
在nginx目录下
./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --add-module=/opt/download/ngx_devel_kit-0.3.0 --add-module=/opt/download/lua-nginx-module-0.10.9rc7
make -j 4 && make install
4、加载lua库,加入到ld.so.conf文件
echo "/usr/local/LuaJIT/lib"/etc/ld.so.conf
5.nginx调用lua的模块指令
nginx的可插拨模块化加载执行,共11个处理阶段
set_by_lua 设置nginx变量,可以实现复杂的赋值逻辑
set_by_lua_file
access_by_lua 请求访问阶段处理,用于访问控制
access_by_lua_file
content_by_lua
content_by_lua_file 内容处理器,接收请求处理并输出响应
6.nginx lua api
7.实战场景 --灰度发布
按照一定的关系区别,分部分的代码进行上线,是代码的发布能够平滑过渡上线
1.用户的信息cookie等信息区别
2.根据用户的ip地址
流程:
客户端----->nginx + lua ------->1.校验ip redis(缓冲新的ip)
2.成功,访问新服务器
3.不成功,访问老服务器
查看本地端口
netstat -luntp
示例:
location / {
default_type "text/html";
content_by_lua_file /opt/app/lua/dep.lua; //lua脚本
}
十丶nginx常见问题
1.相同server_name 多个虚拟主机优先级访问
示例:
server {
listen 80;
server_name testserver1 test;
location {
}
}
server {
listen 80;
server_name testserver2 test;
location {
}
}
优先读取最先读取到的配置作为ip访问的servername
2.location匹配优先级
= 完全匹配
^~ 以什么开头的,前缀匹配
~ \~* 表示执行一个正则匹配 ~*不区分大小写 ~区分大小写
3.try_files使用
检查文件是否存
location / {
try_files $uri $uri/ @page;
}
location @page {
proxy_pass http://127.0.0.1:8080
}
步骤:1.先$uri是否有对应文件,有直接返回
2.没有$uri加个/,再看,有返回
3.没有用@page处理
4.nginx的alias和root区别
root 表示程序是哪个位置. 相当于用root的代替域名
alias 相当于用 alias代替cat.png的前面所有
5.用什么方法传递用户的真实ip
用户IP1
set x_real_ip=$remote_addr
后端服务
$x_real_ip=IP1
6.其他
nginx: 413 request Entity Too large
1.用户上传文件限制 client_max_body_size
502 bad getway
2.后端服务无响应
504 getway time-out
3.后端服务执行超时
十一丶nginx性能优化
1.性能优化考虑点
1.当前系统结构瓶颈
观察指标,压力测试 top
2.了解商业模式
接口业务类型,系统层次化结构
3.性能与安全
2.压测工具ab
1.安装
yum install httpd-tools
2.使用
ab -n 2000 -c 5 http://127.0.0.1
-n 总的请求次数
-c 并发数
-k 是否开启长连接
3.系统与 nginx 性能优化
网络:
系统:
服务:
程序:
数据库丶底层服务:
文件句柄:
linux\unix 一切皆文件,文件句柄就是一个索引.默认1024个
设置方式:
系统全局修改,用户居不下修改,进程局部性修改
配置:
cd /etc/security/limits.d
vim 下面的文件
添加:
root soft nofile 65535 //一般设置1w多久差不多了
root hard nofile 65535
* soft nofile 65535 //对所有用户
* hard nofile 65535
针对进程:
在nginx.conf下配置
worker_rlimit_nofile 35535; //针对nginx的进程
4.系统与nginx的性能优化
cpu的亲和
把进程通常不会再处理器之间频繁迁移进程迁移的频率小,减少性能损耗
当前物理cpu
cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l
线程
cat /proc/cpuinfo | grep "processor" | wc -l
核数:
cat /proc/cpuinfo | grep "cpu cores" | uniq
配置:
worker_processes 1; #启动多少个work进程.官方建议配置成物理cpu进程数
worker_cpu_affinity 00000000000000001 .........; #绑定到不同的cpu
查看nginx使用的进程数是哪一个
ps -eo pid,args,psr | grep [n]ginx
worker_cpu_affinity 10101010..... 区分..
worker_cpu_affinity auto; //自动区分cpu
5.nginx配置优化解析
user name; //不建议用root
error_log //error的日志级别 用warn
worker_rlimit_nofile 65535; //文件句柄对进程的限制
events { //时间驱动器
use epoll;
worker_connections 10240; //限制每个work进程能处理多少连接
}
http {
charset uft-8; //字符集
access_log off; //建议关闭不用的日志,关闭到server级,不要写在http
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_disable "MSIE [1-6]\."; //IE1-6不进行压缩
gzip_http_version 1.1;
}
十二丶基于nginx架构的安全篇
1.常见的恶意行为
爬虫行为和恶意抓取,盗用资源
基础防盗链功能--目的不让恶意用户轻易的爬取网站对外数据
secure_link_module--对数据安全性提高加密验证和时效性,适合如核心安全重要数据
access_module--对后台用户服务的数据提供ip防控
2.常见的应用层攻击手段
后台密码撞库--通过猜测密码字典不断对后台系统登录性尝试,获取后台登录密码
1.后台登录密码复杂的
2.access_module--对后台用户服务的数据提供ip防控
3.预警机制 nginx + lua
文件上传漏洞--利用这些可以上传的接口将恶意代码植入到服务器中,通过url去访问执行代码
//上传以php结尾的返回403
location ^~ /upload{
root /opt/app/images;
if($request_filename ~* (.*)\.php){
return 403;
}
}
sql注入--利用未过滤/未审核用户输入的攻击方法,让应用运行本不应该运行的sql代码
sql注入场景
模拟:
安装数据库: yum install mariadb-server mariadb
启动数据库: systemctl start mariadb.service
查看是否启动:systemctl status mariadb.service
更新密码
mysqladmin -u root password "MTIzNHF3ZXI=";
授权
grant all on *.* to'root'@'113.194.58.75' identified by 'MTIzNHF3ZXI=';
flush privileges;
增加用户和授权
CREATE USER '用户名'@'localhost或者%' IDENTIFIED BY '密码';
grant all on *.* to'root'@'%' identified by 'root';
具体参考:http://www.cnblogs.com/conanwang/p/5932579.html
主从复制
vim /ect/my.cnf
在[mysqld]段的最后添加以下内容
skip_name_resolve = ON
innodb_file_per_table = ON
server-id = 2 (一般为ip)
relay-log = master-log (自定义二进制日志文件名) 从的这里改成slave
从库最好加上
read-only=1
从:
change master to master_host='192.168.31.26', master_user='root', master_password='root', master_port=3306, master_log_file='master-log.000001', master_log_pos=245, master_connect_retry=30;
start slave; 开启主从同步
show slave status\G; 查看同步状态
3.nginx防攻击策略
4.场景: nginx + lua 的安全 waf 防火墙
拦截cookie类型攻击
拦截异常post请求
拦截cc攻击
拦截url
拦截arg
实现:https://github.com/loveshell/ngx_lua_waf
yum install git
git clone https://github.com/loveshell/ngx_lua_waf.git
十三丶nginx漏洞和新版本特性
十四丶基于nginx的中间件架构
十五丶文件下载
浏览器访问路径为 location 实质对应的服务器路径为:root + location
location / {
root /usr/local/homepage;
index index.html index.htm;
文件下载
if ($request_filename ~* ^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx|apk)$){
add_header Content-Disposition: 'attachment;';
}
}
Java
1
https://gitee.com/mengcan/study-note.git
git@gitee.com:mengcan/study-note.git
mengcan
study-note
学习笔记
master

搜索帮助