nginx在请求路径时返回文件

时间:2018-10-20 04:25:16

标签: nginx

作为标题描述,当我请求“ http://example.com/test/poster/”时,我想获取真实文件“ /home/vagrant/example/resouces/views/posters.html”。

这是我的nginx配置:

server_name example.com;
root /home/vagrant/example/public;
index index.html;

location / {
    return 404;
}

location ~ ^/test/poster/?$ {
    default_type text/html;
    index posters.html;
    alias /home/vagrant/example/resouces/views/;
}

但是当我发出请求时,我得到404响应。我搜索nginx错误日志,得到以下信息:

2018/10/20 11:54:41 [debug] 4690#4690: *180 http script copy: "/home/vagrant/example/resouces/views/"
2018/10/20 11:54:41 [debug] 4690#4690: *180 open index "/home/vagrant/example/resouces/views/posters.html"
2018/10/20 11:54:41 [debug] 4690#4690: *180 internal redirect: "/test/poster/posters.html?"
2018/10/20 11:54:41 [debug] 4690#4690: *180 rewrite phase: 1

这是我的问题,当打开索引时,它已找到文件,为什么要执行内部重定向?

我终于通过使用try_files来解决它,我只想知道为什么当我在一个位置块中使用带索引的别名时,它为什么不起作用。谢谢!

2 个答案:

答案 0 :(得分:0)

index module执行多阶段处理。

如果URI以/结尾并且被发现是location中当前正在处理请求的目录,则Nginx将检查与{{1}中的名称匹配的文件}指令的值。

如果找到匹配的文件,则将通过附加该名称来更改URI,然后将开始搜索index以处理新URI。

在您的情况下,URI location与原始/test/poster/posters.html不匹配,因此找不到location文件。

答案 1 :(得分:0)

  1. 如果uri以'/'结尾,nginx会将索引文件和别名路径合并为全路径索引文件,并检查该文件是否存在。
  2. 如果存在,则将开始内部重定向;如果不存在,nginx将检查别名路径是否为目录。
  3. 如果别名路径是dir,则nginx将尝试其他索引文件,直到返回403;如果别名路径不是dir,nginx将直接返回404。

  1. 如果uri不以'/'结尾,nginx将直接使用别名路径。
  2. 如果别名路径是文件但不存在,则nginx将返回404;如果别名路径是dir,则nginx将返回301,并在末尾加上斜杠后加上原始uri。
相关问题