nginx 图片访问404 (使用location中使用 root,alias的区别)

问题描述:

在/data/code_img/文件下有不少验证码图片,想将他们展现出来
但愿经过 http://127.0.0.1/img/1.png 这种形式访问到对应图片,刚开始nginx中配置以下html

server {
        server_name location;
        root /data/code_img;
        location = / {
        }

        location = /index.html {

        }

        location ^~  /img/ {
        root /data/code_img/;
       }


        location ^~ /static {
        }

        location  / {
                 proxy_pass         http://127.0.0.1:80/;
                 proxy_redirect     off;
                 proxy_set_header   Host             $host;
                 proxy_set_header   X-Real-IP        $remote_addr;
                 proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
    




}

图片在对应文件下存在时,仍难访问失败,返回404nginx

解决问题

经过日志发现,实际访问http://127.0.0.1/img/1.png 时,请求的文件地址为 /data/code_img/img/1.png ,而这个路径是不存在的,因此返回404浏览器

才想到是root 路径配置问题。
应该将日志

location ^~  /img/ {
        root /data/code_img/;
       }

改成code

location ^~ /img/ {
        alias  /data/imgs/;
    }

这样,再次访问时就能够正常访问了server

当我一样浏览器访问  http://127.0.0.1/img/1.pnghtm

使用root 会映射为 /data/code_img/img/1.png图片

使用alias 会直接映射 /data/code_img/1.pngrem

相关文章
相关标签/搜索