yujianfang / blog

0 stars 0 forks source link

Nginx学习笔记 #17

Open yujianfang opened 5 years ago

yujianfang commented 5 years ago

nginx安装

.环境确认

一 四项确认: 1.确认系统网络可用

  1. 确认yum可用 3.确认关闭iptables规则 iptables -F(关闭)
  2. 确认停用selinux: getenforce (查看selinux是否开启) 二 两项安装: yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake yum -y install wget httpd-tool vims 三. 一次初始化 cd /opt/;mkdir app download logs work backup

    nginx安装

    配置yum源 1.链接 http://nginx.org/en/linux_packages.html#stable 拷贝: [nginx] name=nginx repo baseurl=http://nginx.org/packages/CentOS/7/$basearch/ gpgcheck=0 enabled=1 2.配置yum源 vim /etc/yum.repos.d/nginx.repo

  3. yum intall nginx nginx -v 查看版本 nginx -V (查看参数)

基本参数使用

rpm -ql nginx(查看nginx安装目录) etc:放置配置 /etc/logrotate.d/nginx 配置 文件 Nginx日志轮转,用于logrotate服务的日志切割

/etc/nginx /etc/nginx/nginx.conf /etc/nginx/conf.d /etc/nginx/confg.d/default.conf 目录、配置文件 Ngix主配置


/etc/nginx/fastcgi_params /etc/nginx/uwsgi_params /etc/nginx/scgi_params 配置文件 cgi配置 相关,fastcgi相关配置


/etc/nginx/koi-utf /etc/nginx/koi-win /etc/nginx/win-utf 配置文件 编码转化映射转化文件


/etc/nginx/mime.types 配置文件 设置http协议的Content-type与扩展名的对应关系

/usr/lib/systemd/system/nginx-debug.service /usr/lib/systemd/system/nginx.service /ect/sysconfig/nginx /ect/sysconfig/nginx-debug 配置文件 用于配置出系统守护进程管理器管理方式

/usr/lib64/nginx/modules /ect/nginx/modules 目录 Nginx模块目录

/usr/sbin/ngix /usr/sbin/ngix-debug 命令 Ngix服务的启动管理的终端命令

/usr/share/doc/nginx-1.14.1 /usr/share/doc/nginx-1.14.1/COPYRIGHT /usr/share/man/man8/nginx.8.gz 文件 目录 Nginx的手册和帮助文件 -- /var/log/nginx 目录 Nginx日志目录

nginx -V(编译参数) image image image image image

nginx配置

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;

sendfile        on;
#tcp_nopush     on;

keepalive_timeout  65;

#gzip  on;

include /etc/nginx/conf.d/*.conf;

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

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

"default.conf" 45L, 1093C 2,5 Top 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;
}

# 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请求变量

http请求变量: -arg_PARAMETER、http_HEADER、sent_http_HEADER(HEADER代表请求头,里User-agent) 内置变量 -Nginx内置的 http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log 自定义变量 -自定义

Nginx 模块

Nginx 官方模块 第三方模块 image 配置语法 image nginx -tc /ect/nginx/nginx.conf //检查语法错误 配置demo image 配置语法,限制location,配置默认随机主页 image http内容替换

参数: image -- 文件缓存 image -- 匹配规则 image location{ sub_filter 'text' 'TEXT';#将a标签中的text替换为TEXT sub_filter_once off;#全局替换 }

Ngin请求限制

image

针对连接的配置语法 image

请求限制语法: image http{ limit_con_zone $binary_remote_addr zone=con_zone_name:1m; limit_req_zone $binary_remote_addr zone=req_zone_name:1m rate=1r/s servier{ location{

limit_con_zone=con_zone_name;#请求限制

limit_req zone=req_zone_name burst=3 nodelay;#连接限制

16 limit_req zone=req_zone_name;#连接限制

} } }

ab -n 50 -c 20 url //ab工具, -n 50个请求 -c 并发个数 //ab压测工具

Nginx访问控制

基于IP的访问控制 http_access_module 基于用户的信任登录 image IP image

server{ location ~ ^/2.html{#限制通配到 ~匹配 deny yourIP;#test allow all; } http_access_module 局限: 通过代理访问不能限制 http_x_forwarded_for image

auth

image image location ~ ^/2.html{ auth_basic "auth access test!input your password"; auth_basic_user_file /etc/nginx/auth_conf; } 局限性: 用户信息依赖文件 操作管理机械,效率低下 解决方案:

  1. Nginx 结合LUA实现高效验证
  2. Nginx 和LDAP打通,利用nginx_auth_ldap模块

基于Nginx的中间件架构

一 静态资源WEB服务 二 代理服务 三 负载均衡调度器 SLB 四 动态缓存

静态资源服务器

image 静态资源服务场景

image 配置语法-文件读取 image 作用:sendfile开启的情况下,提高网络的传输效率 image 作用:在kepplive下,提升网络传输实时性 image 压缩:压缩传输 image //压缩比 需要根据服务器情况选择压缩级别 image

image

扩展Nginx压缩模块 image gunzip 浏览器不支持gzip情况下用 image demo server{ location ~ .*.(jpg|gif|png){#以jpg gif png结尾

gzip on;

gzip_http_version_1.1;

gzip_comp_level 2;

root /opt/images; } location ~ ^/download{ #以dowload开头的 gzip_static on; tcp_nopush on; root /opt/code/src; } }

浏览器缓存

http协议定义的缓存机制

expires配置语法

image demp location ~ /.(txt|htmlcss|js)${

expires 24h;

root /opt/code/src; } nginx跨站访问 image

nginx防盗链 目的:防止资源被盗用 首要方式:区别那些请求是正常请求 基于http_refer防盗链模块 配置 image http_refer代表被 哪个地址引用 location ~ ..(jpg|gif|png)${ valid_referers none blocked localhost ~/google;# none 代表没有refer block代表非http localhost代表自己的ip ~ 匹配的方式 if($invalid_referer){ return 403; } root /opt/code/src; }

代理服务

正向代理:代理的对象是客户端 反向代理:代理的对象是服务器 image image nginx reload命令 nginx -s reload -c /etc/nginx/nginx/conf

正向代理: location /{ if( $http_x_forwarded_for !~* "^yourip"){# http_x_forward_for 携带所有ip return 403; } root /opt/code/src; } 在 your_ip的服务器上 resolver 8.8.8.8; #DNS解析 location / { proxy_pass http://$http_host$requst_uri; } 通过浏览器代理即可访问 其他配置-缓冲区 image 重定向 image 头信息 image 超时 image demo image

nginx负载均衡

GSLB 全局负载均衡 SLB 局部负载均衡(用的最多)

分为四层负载均衡和七层负载均衡 四层可以支持到TCP/IP层的负载 七层负载均衡 在应用层 http信息等(nginx是典型的7层负载均衡 SLB) 负载的核心是 proxy_pass 转发到一组 upstream server 配置语法(必须在http层) image demo 在负载服务器上 http{ upstrem test{ server yourip:yourport1; server yourip:yourport2; server yourip:yourport3; } server{ location /{ proxy_pass http://imooc; include proxy_params; } } } upstream 举例 支持域名 socket等 image

image 调度算法: image demo //ip_hash 当出现代理后就会错乱等问题 http{ upstream test{ ip_hash; ... } } image upstream test{ hash $request_url;#基于utl的hash } 缓存服务(减少服务端压力) image image image demo: image image 如何清理缓存 方法一: rm -fr 缓存目录 第三方扩展模块 ngx_cache_purge 如何让部分页面不缓存 image image 大文件的分片请求 image

深度学习

Nginx动静分离 动态请求才需要经过程序框架 http{ upstream java_api{ server 127.0.0.1:8080; } server{

动态规则

location ~ .jsp${ proxy_pass http://java_api; index index.html index.htm; }

静态规则

location ~ .(jpg|png|gif)${ expires 1h; zip on; } } } Nginx rewrite 规则 实现url重写 1) URL访问跳转,支持开发设计 页面跳转、兼容性支持、展示效果等 2) SEO优化 3)维护 后台维护、流量转发等 4)安全 语法 image rewrite ^(.*)/pages/maintain.html break;//网站维护时重定向

终端 pcretest //正则测试命令 image if(!-f request_filename){ #判断文件是否存在-f } rewrite 规则优先级 执行 server块的rewrite指令 执行location匹配 执行rewrite中的规则

nginx高级模块 image secure_linek_modle配置语法 image demo location /{ secure_link $arg_md5,$arg_expires;# /download?md5=8e9e99e&expires=12333 secure_link_md5 "secure_link_expires&uri imooc"; if($secure_link = ""){ return 403; } if($secure_link = 0){ return 401; } }

geoip_module模块 (读取基于ip的 地域信息) image yum install nginx-module-geoip 使用场景:

  1. 区别国内外http访问规则 2.区别国内城市低于作http访问限制 image http{ geoip_county /ect/../GeoIP.dat; geoip_city /ect/.../GeoLiteCity.dat; location /{ if(geoip_country_code != CN){ retrun 403; } root /opt/code/src; index index.html; } location /myid{ # 查看ip信息 default_type text/plain; retrun 200 "$remote_addr $geoip_country_name $geoip)country_code $geoip_city"; } } https服务 http不安全 1.传输数据被中间人盗用、信息泄露 2.数据内容劫持、篡改 https对数据进行加密以及身份验证 image 生成CA证书(形成自签证书) 生成密钥和CA证书 命令 openssl version nginx -V (看是否有--with-http_ssl_module) 步骤 一、生成key密钥 步骤二、生成证书签名请求文件(csr文件) 步骤三、生成证书签名文件(CA文件) nginx 目录 mkdir ssl_key openssl genrsa -idea -out yourname.key 1024 (genrsa 加密算法 1024位数越高精度越高) 生成请求csr证书 opensll -req -new -key yourname.key -out yourname.csr 生成crt证书: openssl x509 -req -days 3650 -in yourname.csr -signkey yourname.key -out yourname.crt (-days 不填默认一个月,应填上) image

image 直接通过key生成crt openssl req -days 3650 -x509 -sha256 -nodes -newkeyrsa:2048 -keyout yourname.key -out your_apple_crt (-sha256 自签算法 newkeyrsa:2048苹果自签证书,-keyout不需要输入密码)

openssl rsa -in ./yourkey.key -out ./youname_nopas_key #不需要保护码 https服务优化 方法一.激活keepalive长连接 方法二 设置ssl session缓存 server{ keepalive_timeout 100; ssl on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; } Nginx 与lua开发 Nginx与lua灰度发布 Lua 是一个简洁、轻量、可扩展的脚本语言 Nginx+Lua优势 充分结合Nginx的并并发处理epoll优势和lua的轻量实现简单的功能切高并发场景 yum install lua //安装lua image 注释: -- hang行注释 --[[ 块注释 --]] 变量: image lua变量如果没有特殊说明是全局变量 image image image image

  1. LuaJIT 下载LuaJIT (更高效) 2.ngx_devel_kit 和lua-nginx-module 3.重新编译Nginx http://www.imooc.com/article/19597 image

灰度发布:让部分用户或部分ip访问

yum install memcached //下载memcached

location /{ default_type 'text/html'; content_by_lua_file /opt/code/src/lua }

常见问题: 1.相同server_name 多个虚机主机优先级访问 根据conf排序,conf排序靠前则优先匹配

  1. location匹配优先级 = 进行普通字符精确匹配,也就是完全匹配 ^~ 表示普通字符匹配,使用前缀匹配 ~\~* 表示执行一个正则匹配()

Nginx try_files 的使用 顺序检查文件是否存在 location /{ try_files $urL $uri /index.php; # urL是否存在,不存在则去/index.php中处理 最后一个代表动态语言

nginx alias 和root区别 location /request_path_image/{ root /location_path/image; } image image 用什么方法传递用户的真是ip set _x_real_ip = $remote_addr;//通过与第一级代理协商

Nginx :413 Request Entity Too Large 1.用户上传文件限制 client_max_body_size;

  1. 502 bad gateway 后端服务无响应
  2. 504 Gateway Time_out 后端服务执行超时

Nginx 性能优化

1.性能优化考虑点 1) 当前系统结构瓶颈 (观察指标、压力测试) 2) 了解业务模型(接口业务类型、系统层次化结构) 3)性能与安全 2.压测工具 ab 1.安装 yum install httpd-tools /带有ab 使用 : ab -n 2000 -c 2 http://localhost -n 总的请求数 -k 是否开启长连接 -c 并发数 nginx 在处理静态资源上是非常高效的 3.系统与Nginx性能优化 网络 系统 服务 程序 数据库 最常见的性能优化 文件句柄: linux\unix 一切皆文件,文件句柄就是一个索引 设置方式 系统全局性修改、用户局部性修改、进程局部性修改 配置文件: /etc.security/limits.conf 结尾添加 root soft nofile 65535 # 软设置,不会影响,只会通知,一般设置到1w root hard nofile 65535 # 硬设置

//针对进程 nginx/nginx/conf work_rlimit_nofile 35535;#针对于nginx进程设置 cpu 亲和: 把进程同城不会在处理器之间平安迁移进程频率变小,较少 /proc/cpuinfo image nginxconf worker_processes 16; # 启动进程跟当前cpu一致 cpu亲和配置 work_cpu_affinity //哪个位是1则使用哪个cpu image ps -eo pid,args,psr |grep [n]ginx 第二个方式 work_processes 2; work_cpu_affinity 10101010101010;//1代表启用的cpu work_cpu_affinity auto;//nginx自动设置 image

Nginx架构的安全

1.常见的恶意行为 爬虫行为和恶意抓取、资源盗用 基础防盗链功能-目的不让恶意用户能轻易的爬去网站对外数据; secure_link_module-对数据安全性提高加密验证和失效性,适合如核心数据 access_module -对后台、部分用户服务的数据提供IP防控

  1. 常见的应用层攻击手段 后台密码撞库- 通过猜测密码字典不断对后台系统登录性尝试,获取后台登录密码 方法一 后台登录密码复杂度 方法二 access_module 对后台提供IP防控 方法三、预警机制 文件上传漏洞: 利用可以上传文件功能植入恶意代码 http://localhost/upload/1.jpg/1.php nginx 将1.jpg作为php代码执行 location ^~ /upload{ root /opt/code/images; if($request_filename ~(.).php){ return 403;//如果文件名上传时php结尾未见,提示不允许上传 } } sql注入 利用未过滤/未审核用户输入的攻击方法,让程序运行本不该运行的sql代码 mariadb //数据库

  2. Nginx防攻击策略

  3. Nginx+LUA的安全waf防火墙

image lua 防黑配置 image 不生效需要在规则中添加 wafconf下增加对应规则 CCDeny="on" 访问频率限制; CCrate="600/60" 一分钟限制600次

Nginx漏洞和新版本特性

1.查看版本更新描述 2.CVE-2017-7529 文件信息泄露漏洞 1.12.1之后修复

基于Nginx的中间件架构

  1. 静态资源服务 2.代理服务(正向代理与反向代理)
  2. 动静分离

设计评估 硬件: cpu 内存 硬盘 系统: 用户权限、日志目录存放 关联服务: lVS、keeplive、syslog、Fastcgi

配置注意事项: 合理配置(注意context 配置到不同位置影响是不通的) 了解原理(http协议原理、http状态原理、操作系统原理) 关注日志()