Nginx 配置静态文件404问题

来源:互联网 发布:文员基本办公软件 编辑:程序博客网 时间:2024/05/22 06:03
使用Nginx做图片服务器时候,配置之后图片访问一直是  404.
我的配置是
location /api/v1/upload {     root /opt/edu/upload;}



文件放在 
/opt/edu/upload 目录下。

访问

http://localhost/api/v1/upload/api/v1/upload/course/logo/44242acc58f2465c8daf53a2a8b1ec70_add.png

一直是404
日志也是接收到了。但是就是404
10.20.5.247 - - [09/May/2017:13:35:57 +0800] "GET /api/v1/upload/course/logo/44242acc58f2465c8daf53a2a8b1ec70_add.png HTTP/1.1" 404 571 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" "-"




最后发现配置的问题。配置静态路径的两种方式。之前静态的都是直接在URL里写根目录,
所以一直没发现。今天写了一个有前缀的URL,就出现了。


RootCause:

root 配置的意思是,会在root配置的目录后跟上URL,组成对应的文件路径。
即我的访问
http://localhost/api/v1/upload/api/v1/upload/course/logo/44242acc58f2465c8daf53a2a8b1ec70_add.png
最终去寻找的文件路径是
/opt/edu/upload/api/v1/upload/course/logo/44242acc58f2465c8daf53a2a8b1ec70_add.png
而我想要的是
/opt/edu/upload/course/logo/44242acc58f2465c8daf53a2a8b1ec70_add.png

而Nginx提供了另外一个静态路径配置  : alias

alias与root区别

  • 官方root
    1234
    Sets the root directory for requests. For example, with the following configurationlocation /i/ {    root /data/w3;}

The /data/w3/i/top.gif file will be sent in response to the “/i/top.gif” request

  • 官方alias
    1234
    Defines a replacement for the specified location. For example, with the following configurationlocation /i/ {    alias /data/w3/images/;}

on request of “/i/top.gif”, the file /data/w3/images/top.gif will be sent.

当访问/i/top.gif时,root是去/data/w3/i/top.gif请求文件,alias是去/data/w3/images/top.gif请求,也就是说
root响应的路径:配置的路径+完整访问路径(完整的location配置路径+静态文件)
alias响应的路径:配置路径+静态文件(去除location中配置的路径)

最终解决访问:

修改配置为

location /api/v1/upload {     alias /opt/edu/upload/;}


注意

  1. 使用alias时目录名后面一定要加“/”
  2. 一般情况下,在location /中配置root,在location /other中配置alias
















2 0