【问题标题】:nginx return a file when request for pathnginx在请求路径时返回一个文件
【发布时间】:2018-10-20 04:25:16
【问题描述】:

如标题描述,当我请求“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 解决了它,我只是想知道为什么当我在一个位置块中使用带有索引的别名时它不起作用。谢谢!

【问题讨论】:

    标签: nginx


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

    1. 如果uri不以'/'结尾,nginx会直接使用别名路径。
    2. 如果别名路径是文件但不存在,nginx 会返回 404;如果别名路径是 dir,nginx 会返回 301,尾部斜杠附加 origin uri。

    【讨论】:

      【解决方案2】:

      index module 执行一个多阶段进程。

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

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

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

      【讨论】:

      • “发现是一个目录”,你的意思是“/test/poster/”还是别名指令后面的目录?
      • /test/poster/ 是一个 URI,但 alias 指令将其映射到目录 /home/vagrant/example/resouces/views/
      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2022-01-03
      • 2019-02-03
      • 1970-01-01
      相关资源
      最近更新 更多