nginx基本使用 linux(mac下的)
目录结构
编译后会有:conf html logs sbin 四个文件 (其他两个是之前下载的安装包)
- conf:配置文件
- html:页面资源
- logs:日志
- sbin:启动文件,nginx主程序
运行后多了文件:<font style="color:rgb(51,51,51);">client_body_temp fastcgi_temp proxy_temp scgi_temp</font>
这些都是临时文件,可忽略
运行原理
master主进程:
Worker为子进程
nginx配置基础
- 基础配置
# 工作worker子进程(小于cpu数:并行 -- 大于CPU数:并发)
worker_processes 1;# worker的最大连接
events {worker_connections 1024;
}http {# include:引入其他配置文件# mime.types:请求头(发送类型)# default_type:默认发送类型include mime.types;default_type application/octet-stream;# 数据零拷贝sendfile on;# 长连接 时间keepalive_timeout 65;# 虚拟主机vhost(nginx可配置多个主机)server {# nginx端口号listen 80;# 主机名server_name localhost;# http://localhost:80/【localtion中的uri】location / {root html;index index.html index.htm;}# 服务器端发生错误的时候,转到/50x.html地址页面# 转到/50x.html的时候后,会在html文件夹中,寻找50x.html页面error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
}
<font style="color:rgb(38, 38, 38);background-color:rgb(245, 245, 245);">mime.types</font>
请求头类型
types {text/html html htm shtml;text/css css;text/xml xml;image/gif gif;image/jpeg jpeg jpg;application/javascript js;application/atom+xml atom;application/rss+xml rss;text/mathml mml;text/plain txt;text/vnd.sun.j2me.app-descriptor jad;text/vnd.wap.wml wml;text/x-component htc;image/avif avif;image/png png;image/svg+xml svg svgz;image/tiff tif tiff;image/vnd.wap.wbmp wbmp;image/webp webp;image/x-icon ico;image/x-jng jng;image/x-ms-bmp bmp;font/woff woff;font/woff2 woff2;application/java-archive jar war ear;application/json json;application/mac-binhex40 hqx;application/msword doc;application/pdf pdf;application/postscript ps eps ai;application/rtf rtf;application/vnd.apple.mpegurl m3u8;application/vnd.google-earth.kml+xml kml;application/vnd.google-earth.kmz kmz;application/vnd.ms-excel xls;application/vnd.ms-fontobject eot;application/vnd.ms-powerpoint ppt;application/vnd.oasis.opendocument.graphics odg;application/vnd.oasis.opendocument.presentation odp;application/vnd.oasis.opendocument.spreadsheet ods;application/vnd.oasis.opendocument.text odt;application/vnd.openxmlformats-officedocument.presentationml.presentationpptx;application/vnd.openxmlformats-officedocument.spreadsheetml.sheetxlsx;application/vnd.openxmlformats-officedocument.wordprocessingml.documentdocx;application/vnd.wap.wmlc wmlc;application/wasm wasm;application/x-7z-compressed 7z;application/x-cocoa cco;application/x-java-archive-diff jardiff;application/x-java-jnlp-file jnlp;application/x-makeself run;application/x-perl pl pm;application/x-pilot prc pdb;application/x-rar-compressed rar;application/x-redhat-package-manager rpm;application/x-sea sea;application/x-shockwave-flash swf;application/x-stuffit sit;application/x-tcl tcl tk;application/x-x509-ca-cert der pem crt;application/x-xpinstall xpi;application/xhtml+xml xhtml;application/xspf+xml xspf;application/zip zip;application/octet-stream bin exe dll;application/octet-stream deb;application/octet-stream dmg;application/octet-stream iso img;application/octet-stream msi msp msm;audio/midi mid midi kar;audio/mpeg mp3;audio/ogg ogg;audio/x-m4a m4a;audio/x-realaudio ra;video/3gpp 3gpp 3gp;video/mp2t ts;video/mp4 mp4;video/mpeg mpeg mpg;video/quicktime mov;video/webm webm;video/x-flv flv;video/x-m4v m4v;video/x-mng mng;video/x-ms-asf asx asf;video/x-ms-wmv wmv;video/x-msvideo avi;
}
- 开启数据零拷贝工作比较
没开启sendfile:nginx读取到html,然后存入缓存,接着将缓存内容发给网络接口,网络接口发送给互联网
开启sendfile:nginx不缓存html了,直接给网络接口发送信号,让网络接口直接来读取html,然后发送到互联网
- 全部配置
#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.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 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.html 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.html index.htm;# }#}
虚拟主机配置
域名配置
将域名绑定ip
不同端口访问不同资源
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80;server_name localhost;location / {root /www/video;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}server {listen 81;server_name localhost;location / {root /www/www;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}}
不同域名访问同一资源
匹配
不同的域名,都会匹配到80端口
server {listen 80;server_name www.xingheng.cn a.xingheng.cn;location / {root /www/video;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
匹配规则
- 通配符匹配
server_name *.mmban.com
- 通配符结束匹配
server_name vod.*;
- 正则匹配
server_name ~^[0-9]+\.mmban\.com$;
反向代理
正向代理与反向代理
主要区别在于这两种方式的作用不同,他们的本质其实是一样的(请求转发),代理代理,就是代替某个东西去做什么
- 一个是代理客户端,就是代理用户,去访问外网服务器
- 一个是代理服务器,就是代理服务器,让用户可以访问
代理规则
proxy_pass:代理路径 – 有了proxy_pass就不会访问root /www/video; index index.html index.html;
了
location / {root /www/video;index index.html index.htm;proxy_pass http://xingheng.com/;
}
基于反向代理的负载均衡
使用
# httpd是负载均衡组的名字,可自定义
upstream httpd {server 192.168.44.102:80;server 192.168.43.103:80;
}location / {root /www/video;index index.html index.htm;proxy_pass http://httpd # 有这个上面的静态资源就不访问了}
常用策略
upstream httpd {server 127.0.0.1:8050 weight=10 down;server 127.0.0.1:8060 weight=1;server 127.0.0.1:8060 weight=1 backup;
}
- weight:默认为1 weight越大,负载的权重就越大。
- down:表示当前的server暂时不参与负载
- backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。(备用服务器)
了解策略
- ip_hash:根据客户端的ip地址转发同一台服务器,可以保持回话。
- least_conn:最少连接访问
- url_hash:根据用户访问的url定向转发请求
- fair:根据后端服务器响应时间转发请求
动静分离
location配置静态资源
server {listen 80;server_name localhost;# / 的匹配优先级最低location / {proxy_pass http://127.0.0.1:8080;}# 匹配路径是/js的路径location /js {root htmlindex index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}
}
路径匹配规则
location前缀规则
/ 通用匹配,任何请求都会匹配到。
= 精准匹配,不是以指定模式开头
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
^~ 非正则匹配,匹配以指定模式开头的location
location匹配顺序
- 多个正则location直接按书写顺序匹配,成功后就不会继续往后面匹配
- 普通(非正则)location会一直往下,直到找到匹配度最高的(最大前缀匹配)
- 当普通location与正则location同时存在,如果正则匹配成功,则不会再执行普通匹配
- 所有类型location存在时,“=”匹配 > “^~”匹配 > 正则匹配 > 普通(最大前缀匹配)
location ~*/(css|img|js) {root /usr/local/nginx/static;index index.html index.htm;
}
alias与root
location /css/ {alias /usr/local/nginx/static/css/;index index.html index.htm;
}
location /css {alias /usr/local/nginx/static;index index.html index.htm;
}
alias和root指令功能类似,都是指定访问的资源,不过配置上有些区别:
**root**
** 是“加在 URI 前面的前缀”
**alias**
**是“把整个 location 路径替换掉”**root**
** 通常用于匹配路径不变的情况
**alias**
**用于重写某段 URL 到另一路径**root**
对/
不敏感
**alias**
的路径末尾最好加/
,否则容易匹配失败
例如:代码中的代码路径,现在要访问/css/style.css
root是直接拼接:/usr/local/nginx/static + /css/style.css
alias是裁剪:/css/style.css
匹配,裁剪location
后的路径/css/
,变为style.css
,然后将style.css
拼接到/usr/local/nginx/static/css/
后面
UrlRewrite
入门案例
location / {rewrite ^/xingheng/(.*)$ /index.jsp?pageName=$1 break;proxy_pass http://127.0.0.1:8080;
}
如果访问呢的路径匹配到了/xingheng
,那么就转向访问http://127.0.0.1:8080/index.jsp?pageName=?
路径
也就是说,如果匹配到了rewirte终点额正则表达式,那么就会讲后面的路径拼接到proxy_pass中设置的路径后面
规则
rewrite是实现URL重写的关键指令,根据regex (正则表达式)部分内容,重定向到replacement,结尾是flag标记。
格式:
rewrite <regex> <replacement> [flag];
关键字:正则(regex) 替代内容(replacement) flag标记
关键字:其中关键字error_log不能改变
- 正则:perl兼容正则表达式语句进行规则匹配
- 替代内容:将正则匹配的内容替换成replacement
- flag标记:rewrite支持的flag标记
rewrite参数的标签段位置: <font style="color:rgb(51,51,51);">server,location,if </font>
flag标记说明:
- last :本条规则匹配完成后,继续向下匹配新的location URI规则
- break :本条规则匹配完成即终止,不再匹配后面的任何规则
- redirect :返回302临时重定向,浏览器地址会显示跳转后的URL地址(就是真实地址会带出来)
- permanent :返回301永久重定向,浏览器地址栏会显示跳转后的URL地址
防盗链
防盗链概念
- 所谓盗链,就是别人直接在他们的网站上引用你网站的资源,比如这样:
<img src="http://yourdomain.com/images/logo.png">
这样一来,对方的网页访问者会去访问你的服务器资源,消耗你的带宽资源,却不给你任何访问量或广告收益,所以我们需要防盗链
- referer
假设你在 https://a.com/index.html
这个页面上,有一张图片:
<img src="https://b.com/images/logo.png">
当用户访问 a.com/index.html
页面时,浏览器会自动去加载图片,这个时候对 b.com/images/logo.png
的请求里,HTTP 请求头中会自动带上:
Referer: https://a.com/index.html
也就是说,服务器 **b.com**
可以知道:访问这张图的是从 **a.com**
页面跳过来的。
那么什么时候没有refer呢?直接在浏览器顶部地址输入对应的地址访问就没有referer啦
配置防盗链
- 配置案例
valid_referers 192.168.44.101;
if ($invalid_referer) {return 403;
}
- 详细规则
valid_referers none | blocked | server_names | strings ....;
- `**<font style="color:#DF2A3F;">none</font>**`<font style="color:rgb(51,51,51);">, 检测 Referer 头域不存在的情况,如果不存在,那么就可以访问(即使是本网站访问也不行)</font>
- `<font style="color:rgb(51,51,51);">blocked</font>`<font style="color:rgb(51,51,51);">,检测 Referer 头域的值被防火墙或者代理服务器删除或伪装的情况。这种情况该头域的值不以 “http://” 或 “https://” 开头。 </font>
- `<font style="color:rgb(51,51,51);">server_names</font>`<font style="color:rgb(51,51,51);"> ,设置一个或多个 URL ,检测 Referer 头域的值是否是这些 URL 中的某一个。</font>
使用curl测试
安装
yum install -y curl
常用命令
- 看某个地址能否访问
curl -I http://192.168.44.101/img/logo.png
- 带referer
# http://baidu.com就是refer
curl -e "http://baidu.com" -I http://192.168.44.101/img/logo.png
高可用配置
keepalive高可用原理
keepalive安装
yum install -y keepalived
keepalive配置
- 打开文件
# 打开keeplived.conf
cd /etc/keepalived
vi keepalived.conf
- 配置文件
第一台机器
! Configuration File for keepalivedglobal_defs {router_id lb111
}vrrp_instance VI_1 {# 当前机器是masterstate MASTER# 网卡名称(改)interface enp0s5virtual_router_id 51# 优先级,竞选成功的优先级priority 100# 间隔检测时间advert_int 1# 多个keepalived通信配置(相同即可)authentication {auth_type PASSauth_pass 1111}# 虚拟地址(改)virtual_ipaddress {192.168.33.200}
}
注:interface需要改成自己的网卡地址,通过ip addr
获取
第二台机器
! Configuration File for keepalivedglobal_defs {router_id lb111
}vrrp_instance VI_1 {# 当前机器是backupstate BACKUP# 网卡名称interface enp0s5virtual_router_id 51# 优先级,竞选成功的优先级priority 100# 间隔检测时间advert_int 1# 多个keepalived通信配置(相同即可)authentication {auth_type PASSauth_pass 1111}# 虚拟地址virtual_ipaddress {192.168.33.200}
}
- 启动服务
systemctl start keepalived
查看状态:
systemctl status keepalived
查看现有ip:
! Configuration File for keepalivedglobal_defs {notification_email {acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.locsmtp_server 192.168.200.1smtp_connect_timeout 30router_id LVS_DEVELvrrp_skip_check_adv_addrvrrp_strictvrrp_garp_interval 0vrrp_gna_interval 0
}vrrp_instance VI_1 {state MASTERinterface eth0virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.200.16192.168.200.17192.168.200.18}
}virtual_server 192.168.200.100 443 {delay_loop 6lb_algo rrlb_kind NATpersistence_timeout 50protocol TCPreal_server 192.168.201.100 443 {weight 1SSL_GET {url {path /digest ff20ad2481f97b1754ef3e12ecd3a9cc}url {path /mrtg/digest 9b3a0c85a887a256d6939da88aabd8cd}connect_timeout 3retry 3delay_before_retry 3}}
}virtual_server 10.10.10.2 1358 {delay_loop 6lb_algo rrlb_kind NATpersistence_timeout 50protocol TCPsorry_server 192.168.200.200 1358real_server 192.168.200.2 1358 {weight 1HTTP_GET {url {path /testurl/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}url {path /testurl2/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}url {path /testurl3/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}connect_timeout 3retry 3delay_before_retry 3}}real_server 192.168.200.3 1358 {weight 1HTTP_GET {url {path /testurl/test.jspdigest 640205b7b0fc66c1ea91c463fac6334c}url {path /testurl2/test.jspdigest 640205b7b0fc66c1ea91c463fac6334c}connect_timeout 3retry 3delay_before_retry 3}}
}virtual_server 10.10.10.3 1358 {delay_loop 3lb_algo rrlb_kind NATpersistence_timeout 50protocol TCPreal_server 192.168.200.4 1358 {weight 1HTTP_GET {url {path /testurl/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}url {path /testurl2/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}url {path /testurl3/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}connect_timeout 3retry 3delay_before_retry 3}}real_server 192.168.200.5 1358 {weight 1HTTP_GET {url {path /testurl/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}url {path /testurl2/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}url {path /testurl3/test.jspdigest 640205b7b0fc66c1ea91c463fac6334d}connect_timeout 3retry 3delay_before_retry 3}}
}
Https证书配置
server
{listen 443 ssl http2 ;server_name www.xinghengdati.cn;ssl_certificate /www/server/panel/vhost/cert/www.xinghengdati.cn/fullchain.pem;ssl_certificate_key /www/server/panel/vhost/cert/www.xinghengdati.cn/privkey.pem;
}