nginx的root和alias的区别

1、结论

  • root匹配的目录:root的值 + location的值 + URL剩余的path

    image.png

  • alias匹配的目录:alias的值 + URL剩余的path,抛弃location的值

    image.png

2、location的最左匹配原则

location /bar {
    root /home/hfy/;
}

http://example.com/foo/bar/hello.html不会命中该location,因为从url中的/foo开始匹配,与location /bar不一致,不会命中,如果url更改为http://example.com/bar/hello.html 才会命中该规则

3、index index.html
location内部其实默认配置了一条规则index index.html

  • 访问http://example.com/foo/bar/时,返回index指定的文件
  • 在访问http://example.com/foo/bar,如果匹配到文件夹,nginx会自动301重定向为http://example.com/foo/bar/,并返回index指定的文件

4、URL末尾斜杠/
http://example.com/foo/bar/:表示想要访问bar文件夹
http://example.com/foo/bar:表示想要访问bar文件,如果是文件夹nginx会自动重定向为http://example.com/foo/bar/

5、root最后的斜杠

  • location的斜杠:
    • location /foo/:只能匹配http://example.com/foo/
    • location /foo:能匹配http://example.com/foohttp://example.com/foo/
  • 配置:
    • root /home/:只把/home/当做目录
    • root /home:把/home当做目录,或者文件

6、alias最后的斜杠

  • location的斜杠:
    • location /foo/:表示访问文件夹
    • location /foo:表示访问文件
  • 配置:
    • alias /home/:只把/home/当做目录
    • alias /home:只把/home当做文件

7、最佳实践

  • location都加斜杠,URL匹配有斜杠,服务器指向文件夹
  • 配置都使用alias,可以忽略location的值,直接用alias+URL其他path
  • alias最后都加斜杠,服务器指向文件夹
  • 访问文件的情况,可以单独开一个指向文件的location
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容