在正式介绍 nginx 中 url 重写时,我们先看看什么是 url 重写?
URL 重写就是首先获得一个进入的 URL 请求然后把它重新写成网站可以处理的另一个 URL 的过程。举个例子来说,如果通过浏览器进来的 URL 是“UserProfile.aspx?ID=1”那么它可以被重写成 “UserProfile/1.aspx”,这样的URL,这样的网址可以更好的被网站所阅读。
可以使用正则表达式去匹配指定的路径,然后借助 rewrite 命令重写指令。
实例:匹配 https://localhost:8080/auth/login url 地址,然后重写到 https://localhost:8080/index.php/auth/login 。如下:
location / { root html; index index.php; rewrite (.*)$ /index.php/$1 }
一般情况下,静态资源我们是不需要进行重写的。可以通过 if 判断是否为文件,文件不进行重写(如:css、js、图片等不重写)。如下:
location / { root html; indexindex.php; # 如果文件不存在,则重写 if ( !-e $request_filename ) { rewrite (.*)$ /index.php/$1 } }
注意:if后面需要空格,且 !-e 是放到前面的。
在 0.7 以后的版本中加入了一个 try_files 指令,配合命名 location,可以部分替代原本常用的 rewrite 配置方式,提高解析效率。
try_files指令:
语法: | try_files file … uri 或 try_files file … = code |
默认值: | 无 |
作用域: | server location |
其作用是按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹)。如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。
实例:尝试 $uri 是否能够访问。如果不能访问,则返回 index.jsp?$uri 。
location / { root html; index index.php; # 你帮我试试 $uri 是否能够访问,不能访问就访问 index.jsp?$uri try_files $uri index.jsp?$uri }