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

问题描述:

在/data/code_img/文件下有很多验证码图片,想将他们展示出来
希望通过 http://127.0.0.1/img/1.png 这种形式访问到对应图片,刚开始nginx中配置如下


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;
        }
    




}

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

解决问题

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

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

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

改为

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

这样,再次访问时就可以正常访问了

当我同样浏览器访问  http://127.0.0.1/img/1.png

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

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

猜你喜欢

转载自www.cnblogs.com/huchong/p/10907514.html