【Linux基础服务教程】Nginx的location写法和URL重写

一、location的写法

作用:匹配客户端访问请求

location [ = | ~ | ~* | ^~ ] uri {
    ..........
}

1. = 精确匹配

location = /test {
    xxxxxxx
}
location = / {
    xxxxxxx
}

2.~ 正则表达式匹配请求(区分大小写)

location ~ /test {
    xxxxxx
}
location ~ \.(jpg|jpeg|gif|png)$ {
    xxxxxxxx
}
location ~ \.php$ {
    xxxxxxxx
}

3. ~* 正则表达式匹配请求(不区分大小写)

location ~* \.php$ {
    xxxxx
}

4.^~ 不以正则的方式匹配请求

xxxx开头

location ^~ /test {
	xxxxxxx
}

5.定义错误页面(404举例)

   error_page 404 /sorry.html;	#指定触发404错误默认文件
   location = /sorry.html {		#默认跳转地址
      root /game;	#网页目录(存放404页面目录)
   }

二、location的优先级排序

  • 如果一个请求被多个location匹配,使用优先级高location处理
  • = , ^~, ~, ~*, location /
location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

三、URL重写

1.语法和用法

location /  {
	xxxxxxxx
	rewrite  uri地址  新uri地址 [标志];
}

注意事项:
1、server, location这2个字段大括号里头都可以写,也可以用if语句
2、rewrite可以存在多条, 依次进行处理
3、旧uri地址支持正则表达式; 新uri支持反向引用
4、旧uri地址匹配客户端时,不包括请求中的参数
5、支持变量的使用

2.标志

  • last
    • 终止本location块中的匹配,将新地址转交给下一个location
  • break
    • 不会将新地址交给其他的location处理,只在本location中处理
  • redirect
    • 临时重定向, 状态码302
  • permanet
    • 永久重定向, 状态码301

3.URL重写例子

改写旧地址的目录

rewrite ^/mp3 http://python.linux.com/music;	#不可靠的
rewrite ^/mp3/(.*)  http://python.linux.com/music/$1;	#改写的同时,支持用户访问的文件不变

域名跳转

rewrite ^/  https://www.baidu.com;	#当前域名跳转到www.baidu.com

实现https自动跳转

修改原来http协议的域名子配置文件

location / {
      root /data/python;
      index index.html;
      if ($host = www.linux.com) {
          rewrite ^/(.*)  https://www.linux.com/$1;
      }
   }