Nginx配置靜態資源文件404 Not Found問題解決方法


在使用nginx做靜態資源服務器時,配置完成后通過瀏覽器訪問一直報404 Not Found錯誤,本人nginx配置信息如下:

location  /images/  {  
      root  /mnt/upload/files ;  
}

所有文件存放在/mnt/upload/files

分析:

發現是配置的問題,配置靜態路徑有兩種方式,之前配置的是直接在URL里寫根目錄,而現在配置是一個有前綴的URL,所以報404 Not Found錯誤了。

root配置會在配置的目錄后跟上URL,組成對應的文件路徑,即想訪問的地址是:

https://blog.yoodb.com/images/a.png

nginx根據配置走的文件路徑是

/mnt/upload/files/images/a.png

而我需要的是

/mnt/upload/files/a.png

而Nginx提供了另外一個靜態路徑配置:alias配置

官方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中配置的路徑)

解決辦法:

location  /images/  {  
      alias  /mnt/upload/files/ ;  
}

注意:使用alias時目錄名后面一定要加“/”;一般情況下,在location/中配置root,在location /*中配置alias


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM