目录
原理
实现原理:
配置文件基础:
#增加每一个location 这个是最简单的实现方法 也好理解 就是太麻烦了 每个都要配置
location /css { #这个会拼接 /usr/local/nginx/static/css
root /usr/local/nginx/static; #资源目录
index index.html index.htm;
}
location /images {
root /usr/local/nginx/static;
index index.html index.htm;
}
location /js {
root /usr/local/nginx/static;
index index.html index.htm;
}
引入正则表达式:
#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;
}
#root用来设置根目录,而alias在接受请求的时候在路径上不会加上location。
原理有了
实战
我们来实战(宝塔版):
我现在有个场景 前后端分离 然后呢 上面说 直接把后台管理静态资源放到nginx里面去
1.把你的静态资源全部cv到该有的nginx目录下
2.然后nginx.conf 配置一下 在server中添加一个(然后其他要加的服务器可以自己加)
反向代理配置多台服务器
#weight 权重比 访问服务器的比例 不过真实的不一定是这样的
#这里可以配置多台服务器
#server 服务器ip 权重
upstream httpds {
server 192.168.44.102 weight=8;
server 192.168.44.103:20219 weight=2;
server 192.168.44.104:20219 weight=1;
}
location / {
proxy_pass http://httpds ;#
}
这里实现资源分离
server {
listen 80;
#存放域名或者你服务的路径
server_name xx.xx.xx.xx;
#后台管理静态资源存放
location / {
#文件目录
root html; #/www/server/nginx/html 宝塔下的目录
#首页的样式
index index.html;
}
location /prod-api {
#反向代理 自己项目ip路径
proxy_pass http://xxx.xxx.xxx.xxx:8080;
}
}
然后就可以网站访问了
结果