使用nginx做图片服务器,用root配置图片目录后期望通过image.xxx.xxx/image/xxx.jpg访问却一直报404错误,但是可以通过image.xxx.xxx/xxx.jpg却可以访问
server {
listen 80;
server_name image.xxx.xxx;
location ^~ /image {
root /storage/images;
}
}
最后发现配置静态路径的两种方式。之前静态的都是直接在URL里写根目录,所以一直没发现。加了一个有前缀的URL,就出现404问题。
查找原因
root 配置的意思是,会在root配置的目录后跟上URL,组成对应的文件路径。
例如URL http://image.xxx.xxx/image/xxx.png
最终去寻找的文件路径是/storage/images/image/xxx.png
而实际图片位置是/storage/images/xxx.png 导致图片404
而通过http://image.xxx.xxx/xxx.png 却能实际找到图片/storage/images/xxx.png
Nginx提供了另外一个静态路径配置 : alias
alias与root区别
官方root
Sets the root directory for requests. For example, with the following configuration
location /i/ {
root /data/w3;
}
The /data/w3/i/top.gif file will be sent in response to the “/i/top.gif” request
官方alias
Defines a replacement for the specified location. For example, with the following configuration
location /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中配置的路径)
修改后的配置
server {
listen 80;
server_name image.xxx.xxx;
location ^~ /image {
alias /storage/images/;
}
}
需要注意的是alia配置的目录后必须加 /
通常情况下 location / 配置中用 root, location /other 使用alias