nginx首次的配置如下

server {
    listen   80;
    server_name  mall.fetosoft.cn;

    location ^~ /images/ {
        root /usr/mall/upload/images;
    }

    #error_page  404              /404.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

服务器上的图片路径:

/usr/mall/upload/images

此时通过 http://mall.fetosoft.cn/images/demo.png 访问总是报404,很是不解,然后查看了一下nginx的error.log日志如下:

2022/10/23 20:26:59 [error] 13449#0: *1370927 open() "/usr/mall/upload/images/images/demo.png" failed (2: No such file or directory),
client: 124.126.181.180, server: mall.fetosoft.cn, request: "GET /images/demo.png HTTP/2.0", host: "mall.fetosoft.cn"

发现请求的文件路径不对,多了一个images文件夹,网上搜索了一下,说root配置的目录后跟上URL,会组成对应的文件路径,即查找文件的路径就变成了/usr/mall/upload/images/images,多了一层images的文件夹,于是根据网上的方法换成了alias,即如下配置:

server {
    listen   80;
    server_name  mall.fetosoft.cn;

    location ^~ /images/ {
        alias /usr/mall/upload/images;
    }

    #error_page  404              /404.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

马上刷新了一下,仍然是404,看了一下错误日志输出如下:

2022/10/23 20:44:15 [error] 14373#0: *1370953 open() "/usr/mall/upload/imagesdemo.png" failed (2: No such file or directory), 
client: 124.126.181.180, server: mall.fetosoft.cn, request: "GET /images/demo.png HTTP/2.0", host: "mall.fetosoft.cn"

这次目录没有多,但是查找文件的路径缺少了一个路径分隔符,如是修改了配置如下:

server {
    listen   80;
    server_name  mall.fetosoft.cn;

    location ^~ /images/ {
        alias /usr/mall/upload/images/;
    }

    #error_page  404              /404.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

再次刷新页面,图片终于出来了!!!

发表评论