nginx location 配置

nginx location指令详解

通过指定模式来与客户端请求的URI相匹配,基本语法如下:location [=|~|~*|^~|@] pattern{……}

1、没有修饰符模糊匹配 :以指定模式开始:

server {
  server_name www.80shihua.com;
  location /aabbcc {
    ……
  }
}

那么,如下是对的:
http://www.80shihua.com/aabbcc
http://www.80shihua.com/aabbcc?s=1
http://www.80shihua.com/aabbcc/
http://www.80shihua.com/aabbccc

2、=精确匹配

server {
server_name www.80shihua.com
  location = /aabbcc {
    ……
  }
}
正确:
http://www.80shihua.com/aabbcc
http://www.80shihua.com/aabbcc?s=1
 
错误:
http://www.80shihua.com/aabbcc/
http://www.80shihua.com/aabbcc

3、~区分大小写匹配 :

server {
server_name baidu.com;
  location ~ ^/aabbcc$ {
    ……
  }
}
正确:
http://www.80shihua.com/aabbcc
http://www.80shihua.com/aabbcc?s=1
 
错误:
http://www.80shihua.com/Aabbcc/
http://www.80shihua.com/AaBbcc

4、~* 表示:指定的正则表达式不区分大小写

server {
server_name baidu.com;
  location ~* ^/aabbcc$ {
    ……
  }
}
正确:
http://www.80shihua.com/Aabbcc
http://www.80shihua.com/Aabbcc?s=1
http://www.80shihua.com/aaBbcc
http://www.80shihua.com/aAbbCc

5、root 、alias指令区别

location /img/ {
    alias /var/www/image/;
}
#若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件
location /img/ {
    root /var/www/image;
}
#若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。

alias是一个目录别名的定义,root则是最上层目录的定义。