基本配置
worker_processes 1; //默認為1,表示開啟一個業務進程
events //事件驅動模塊(){worker_connections 1024; //單個業務進程可接受連接數
}
http{include mime.types; // 引入http mime類型(在外部已經定義好,解析文件的方式)default_type application/octet-stream; //如果沒有在mime.types指定的類型,按照default_type解析sendfile on; //數據零拷貝keepalive_timeout 65; //server { //虛擬主機vhost,一個nginx可以運行多個主機,并且相互之間不干擾listen 80; //監聽的端口號server_name localhost; // 域名或主機名// 重點,下面再說 location / {root html; index index.html index.htm;}eror_page 500 502 503 504 /50x.html; //報錯轉向location = /50x.html{root html; // 重定向}}
}
虛擬主機與域名解析
電腦拿到IP地址之后,會發起TCP/IP請求,
ServerName匹配規則
- 我們可以在統一servername中匹配多個域名
- 完成匹配
- 通配符匹配
- 通配符結束匹配
- 正則匹配
正向,反向代理
下面是一張正向代理的示例,是用戶與服務器主動想要連接外網
下面是反向代理的示例。是由服務方主動提供代理,所以叫反向代理
網關其實就是代理服務器,特點是需要中轉,所以網關的帶寬限制會影響上傳與下載的速度
像這種進出都要經過代理服務器(網關)的叫做隧道式代理,但是有一種性能更高的代理模式叫lvs(DR模型),他上傳需要經過代理服務器,但是連接建立后便從服務方直接連接發起方
location / {// proxy_pass與root二選一proxy_pass http://www.xxxx1.com; //代理到域名# root html; # index index.html index.htm;
}
使用負載均衡,代理到多個ip
// 與server平級
upstream httpds{server xxx1:80; // weight=8 可以附加權重,改變負載均衡策略 down表示下線 backup表示備用server xxx2:80; // weight=2
}location / {// proxy_pass與root二選一proxy_pass http:/httpds; # root html; # index index.html index.htm;
}
動靜分離
location / {proxy_pass http://www.xxxx1.com; //代理到域名
}location /css {root html;index index.html index.htm;
}location /js {root html;index index.html index.htm;
}location /img {root html;index index.html index.htm;
}
上面的書寫方式過于麻煩,我們也可以使用正則表達式
location ~*/(js|css|img) {root html;index index.html index.htm;
}
rewrire
location / {rewrite ^/([0-9]+).html$ /index?pageNum=$1 break; proxy_pass http://www.xxxx1.com; //代理到域名
}
防盜鏈
valid_referers none | blocked | server_names | strings
- none:檢測Referer頭域不存在的情況
- blocked:檢測Referer頭域的值被防火墻或者代理服務器刪除或偽裝的情況,這種情況該頭域的值以http://或者https://開頭
- server_names:設置一個或多個URL,檢測Referer頭域的值是否是這些URL中的某一個
location ~*/(js|css|img) {valid_referers xxxx;root html;if($valid_referer){return 403}index index.html index.htm;
}