1. 程式人生 > >nginx靜態檔案對映root和alias

nginx靜態檔案對映root和alias

使用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