nginx入门3-location配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao__zhen/article/details/86591921

nginx入门3-location配置

1. 基础语法

基础语法有三种:

精准模式

  • location = pattern{}精准匹配

前缀模式

  • location ^~ pattern {} 表示uri以某个常规字符串开头,这个不是正则表达式
  • location pattern {} 普通匹配

正则模式

  • location ~ pattern {} 区分大小写的正则匹配
  • location ~* pattern {} 不区分大小写的正则匹配
  • location !~ pattern {} 大小写敏感不匹配
  • location !~* pattern {} 大小写不敏感不匹配

通用模式

  • location /{} 通用匹配,如果没有其他匹配,任何请求都会匹配到

2. 优先级

  1. 先匹配精准模式,如果命中,直接返回。否则继续匹配前缀模式

  2. 前缀模式中使用最大前缀原则,选出匹配普通匹配(空格)或非正则匹配(^~)的最长location

  3. 若最长前缀location是非正则匹配(^~),则返回该最长前缀location。否则,还需要继续匹配正则模式。

  4. 正则模式的原则是按照正则location定义顺序匹配,第一个匹配的location为正则模式结果

  5. 若正则模式匹配成功,返回正则模式结果。否则,返回前缀模式中的最长前缀location。

(location =) > (location 完整路径) > (location ^~ 路径) > (location ,* 正则顺序) > (location 部分起始路径) > (/)

3. 示例

location ~ test {
        root   html;
        index  index.html index.htm;
    }

当浏览器请求http://222.25.188.1:50352/test1234.html 会通过正则去html目录下寻找test1234.html文件。如果没有会报404错误。

 location / {
            if ($remote_addr != 192.168.0.1){
                return 301;
            }
            root   html;
            index  index.html index.htm;
        }

当浏览器的IP地址不是192.168.0.1,就返回301

if ($http_user_agent ~* firefox) {
			rewrite ^.*$ /firefox.html;
			break;
}

如果客户端浏览器是firefox浏览器就跳转到firefox.html

location /goods {
				rewrite "goods-(\d{1,5})\.html" /goods-ctrl.html;
				root bhz.com;
				index index.html;
		}

猜你喜欢

转载自blog.csdn.net/zhao__zhen/article/details/86591921