index
用于指定站点中的首页,仅当访问的url中uri为”/“时,server下的一级 index才生效指令才生效
upstream apis {ip_hash;server 127.0.0.1:18080;}server {listen 80;server_name 47.95.109.208;keepalive_timeout 60;send_timeout 10s;root /xxx/;index index.html;location ^~ /static/ {access_log off; #对于静态文件,不记录日志expires 7d;}location /api {proxy_set_header Host $host;proxy_set_header X-Real_IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_pass http://apis;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
如果有站点下有一个url有单独的页面
server {listen 80;server_name 47.95.109.208;keepalive_timeout 60;send_timeout 10s;root /xxx/; # 这里的root是一级root,作用域为整个serverindex index.html; #这个是47.95.109.208站点下的首页,即/xxx/index.htmllocation ^~ /static/ {access_log off; #对于静态文件,不记录日志expires 7d;}location /login.html {index login.html #这个是47.95.109.208/login.html 的页面}error_page 500 502 503 504 /50x.html;location = /50x.html {root html; # 这里的root是当前location下,按就近原则取root的值}}
index 的处理逻辑
- 首先对index指令配置的多个文件做顺序查找,看文件是否存在。
- 如果存在,就结束查找过程,把这个文件附加到请求的request_uri后面,并且发起一个内部的redirect。
- 如果全部尝试后都不存在,那么该index指令执行结束,nginx会继续执行content阶段下一个指令的事情。
@
定义一个location段,不能被外部请求所访问,只能用于nginx内部配置指令使用,通常与try_files 结合使用
try_files
server {listen 80;server_name xxx.com;root /mnt/try;location / {try_files $uri @default;}location @default {root /mnt/default;}}
浏览器访问 http://xxx.com/abc/index.html 时,当前的$uri值为/abc/index.html
根据上面的配置
首先会去/mnt/try/abc/index.html找,如果找得到直接返回
如果找不到,则内部跳转导@default到/mnt/default/abc/index.html去找
