2020.02.17
1172
try_files是nginx中http_core核心模块所带的指令,主要是能替代一些rewrite的指令,提高解析效率
try_files是nginx中http_core核心模块所带的指令,主要是能替代一些rewrite的指令,提高解析效率
try_files的语法规则:
格式1:try_files file ... uri; 格式2:try_files file ... =code;
可应用的上下文:server,location段
说明1:按指定的file顺序查找存在的文件,并使用第一个找到的文件进行请求处理
说明2:查找路径是按照给定的root或alias为根路径来查找的
说明3:如果给出的file都没有匹配到,则重新请求最后一个参数给定的uri,就是新的location匹配
说明4:如果是格式2,如果最后一个参数是 = 404 ,若给出的file都没有匹配到,则最后返回404的响应码
需要注意的是:try-files 如果不写上 $uri/,当直接访问一个目录路径时,并不会去匹配目录下的索引页 即 访问127.0.0.1/images/ 不会去访问 127.0.0.1/images/index.html。
实例1 跳转到变量:
server {
listen 8000;
server_name 192.168.119.100;
root html;
index index.html index.php;
location /abc {
try_files /4.html /5.html @qwe; #检测文件4.html和5.html,如果存在正常显示,不存在就去查找@qwe值
}
location @qwe {
rewrite ^/(.*)$ http://www.baidu.com; #跳转到百度页面
}
实例2 跳转指定文件:
server {
listen 8000;
server_name 192.168.119.100;
root html;
index index.php index.html;
location /abc {
try_files /4.html /5.html /6.html;
}
实例3 将请求跳转到后端:
server {
listen 80;
server_name www.imike.me;
root /var/www/www.imike.me/V0.3/www;
index index.html index.htm;
try_files $uri @tornado;
location @tornado {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://tornado;
}
}