负载均衡文件配置
user nobody;
#工作进程数,负载均衡时一般设置为cpu的核数或是其2倍
worker_processes 2;
#worker_connections为要设置的最大并发数
events {
worker_connections 1024;
}
http {
#定义一组待选服务器,遵循轮询原则,若有崩溃服务器则退出该列表
upstream myproject{
#ip_hash可以确保一个用户一直访问的服务器是第一次访问的服务器
#weight代表服务器被访问到的概率,默认为1,越大几率越大
server 192.168.1.5 weight=2;
server 192.168.1.6 weight=1;
server {
listen 8080;
location / {
proxy_pass http://myproject;
}
}
}
nginx缓存文件
Location的正则写法
1.location = / {
# =开头表示精确匹配到已根目录结尾的请求,主机名后不能带任何字符
}
2.location ^ ~ /images/ {
# ^ ~ 表示uri以某个常规的字符串开头,并不是正则表达式
# 匹配任何以/images/ 开头的请求,匹配之后停止往下搜索
}
3.location ~ * \ .(gif | jpg | css | js)${
# ~开头表示区分大小写的正则表达式
# 匹配所有的以 .gif .jpg .css . js结尾的请求
}
如果请求为 /images/444.jpg 将会给2截获,而不会交给3处理4.location = / {
#匹配所有的请求,但是正则表达式和最长字符串会有限匹配
}
比如 :rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3
会对/images/bla_400x800.jpg的请求。重写到 /resizer/$1.$4?width=400&height=800, 并继续匹配
$1:正则表达式第1个()内的内容 $4:正则表达式第4个()内的内容
顺序 no优先级: (location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)
标红部分较为常用!
Rewrite规则
http://seanlook.com/a/we/index.php?id=1&u=str
只对/a/we/index.php重写rewrite
regex replacement [flag];
如果相对域名或参数字符串起作用,可以使用全局变量匹配,也可以使用proxy_pass反向代理。
表明看rewrite和location功能有点像,都能实现跳转,主要区别在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理,可以proxy_pass到其他机器。很多情况下rewrite也会写在location里,它们的执行顺序是:
1.执行server块的rewrite指令
2.执行location匹配
3.执行选定的location中的rewrite指令
如果其中某步URI被重写,则重新循环执行1-3,直到找到真实存在的文件;循环超过10次,则返回500 Internal Server Error错误。