我认为值得明确指出nginx是对前缀而不是文件本身进行操作。在第一种情况下,
location /robots.txt { alias /home/www/static/robots.txt; }
nginx将URL路径中的字符串前缀 替换为,然后将结果用作文件系统路径。表示为伪代码,将类似于:/robots.txt/home/www/static/robots.txt
if urlPath.startsWith("/robots.txt") {
fsPath := "/home/www/static/robots.txt" + urlPath.stripPrefix("/robots.txt")
serveFile(fsPath)
}
之所以如此,/robots.txt是/home/www/static/robots.txt因为/robots.txt删除的/robots.txt前缀是空字符串,并附加空字符串以/home/www/static/robots.txt使其保持不变。但是,/robots.txt1将从送达/home/www/static/robots.txt1且/robots.txt/foobar将从送达/home/www/static/robots.txt/foobar。这些文件可能不存在,导致nginx的发送404响应,并很可能robots.txt不是一个目录无论如何,但nginx的不知道提前,而这是所有基于字符串的前缀,而不是他似乎是一个文件或目录中是否存在尾部斜杠。
而在第二种情况下,
location /robots.txt { root /home/www/static/; }
nginx将字符串插入/home/www/static/URL路径的开头,然后将结果用作文件系统路径。用伪代码,这将类似于:
if urlPath.startsWith("/robots.txt") {
fsPath := "/home/www/static/" + urlPath
serveFile(fsPath)
}
结果与第一种情况完全相同,只是原因不同。有没有前缀剥离,但每URI路径必须包含前缀/robots.txt,那么文件系统路径总是先从/home/www/static//robots.txt这相当于 /home/www/static/robots.txt。
当然,伪代码并不能完全说明问题,例如,nginx不会盲目使用如的原始URL路径/../../../etc/passwd,该try_files伪指令会更改root/ 的行为alias,并且在何处alias可以使用。
=在两种情况下都使用,对吗?还是仅适用于root?另外,请参阅我的编辑-我不是要一次使用两者。:)