nginx中location原理

一、location
Nginx的HTTP配置主

http { ###协议
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
    server { ###服务器
      listen 80;
      server_name localhost;
        location / { ###请求
          root html;
          index index.html index.htm;
        }
      }
}

二、各个区段的含义
1."=“表示精确匹配(例如输入”/data/a"只会匹配到"/data/a")
2."^~“表示一字符串开头进行匹配
3.”~ “开头表示区分大小写的正则匹配
4.”~*" 开头表示不区分大小写的正则匹配
5"/ -"通用匹配(模糊匹配)
三、匹配顺序
1.只要匹配到,进程便会终止,因此在写location的时候一定要注意顺序,因为匹配过程中是按照顺序执行
2.一般精确匹配在首位,通用匹配在最后,区分大小写在不区分大小写之前
四、下面的代码可以更好地理解(可以打开两个终端,分别打开错误日志和登入日志,可以更直观的看出变化)

import re
def fregxeq():
    return "this is my ="
def fregxw():
    return "this is my /"
def fregxd():
    return "this is my ~*"
def fregxD():
    return "this is my ~"
def fregxh():
    return "this is my ^"
#代表nginx中的等于,精确匹配
regxeq = re.compile("/abc/index.html")
#代表nginx中的/
regxw = re.compile("/.*")
#代表nginx中的~,大小写敏感的正则表达式,输入的path不进行大小写转换
regxD = re.compile(".*\.(jpg|png)$")
#代表nginx中的~*,忽略大小写,输入的path路径要转换为小写后进行正则匹配
regxd = re.compile(".*\.(jpg|png)$")
#代表以什么开头的正则表达式
regxh = re.compile("^/images.*")

#一般精确匹配在首位,通用匹配在最后,区分大小写在不区分大小写之前
d = {regxeq:fregxeq,regxD:fregxD,regxd:fregxd,regxh:fregxh,regxw:fregxw}

path = "/images/abc/index.html"
for regx in d:
    try:
        if regx.match(path).group():
            print(d[regx]())
            break
    except Exception as f:
        print(f)

location中加入的部署

#精确的正则表达式注册
	location = /abc/index.html {
		root /data/eq;
		index index.html;
	}

#区分大小写的正则表达式注册
location ~ \.(gif|jpg|jpeg)$ {
	root /data/ignoreuperlower;
	index index.jpg;
} 

#不区分大小写的正则表达式注册
location ~* \.(gif|jpg|jpeg)$ {
	root /data/d;
	index index.jpg;
}

#注册正则表达式以什么开头的path
location ^~ /images.* {
	root /data/images;
	index index.jpg;
}

#匹配任意所有的正则表达式
location / {
	root /usr/share/nginx/html;
	index index.html index.htm;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值