Nginx訪問靜態(tài)資源配置
關(guān)于 alias和root配置的說明:
一般情況下,在nginx配置中的良好習(xí)慣是:
1)在location /中,即路徑為“ / ”時(shí), 配置root目錄;
2)在location /path中,即路徑包含指定內(nèi)容,如“ localtion /imgs ”時(shí), 配置alias虛擬目錄。文章來源地址http://www.zghlxwxcb.cn/news/detail-698648.html
1. 配置修改如下:
# 訪問靜態(tài)資源:直接配置靜態(tài)資源_絕對(duì)路徑,Docker的話,需要配置Docker內(nèi)部Nginx的絕對(duì)路徑
# 配置文件中增加如下內(nèi)容location(配置文件位置:nginx/nginx.conf,
# 新版本配置文件位置:/nginx/conf.d/default.conf)
location /images {
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
# Window服務(wù)器,路徑如 D:/images/;
# ***注***: 1. 路徑分隔符為 / 或 \\ ,而非 \
# 2. 使用alias,最后的" / " 不能缺少
alias /home/nginx-1.22.0/images/; # 絕對(duì)路徑 [ docker需要配置容器內(nèi)絕對(duì)路徑 ]
}
2. 配置相關(guān)屬性說明
nginx默認(rèn)是不允許列出整個(gè)目錄的,如需開啟,使用下方三個(gè)配置項(xiàng):
autoindex on; 開啟目錄列表訪問,這樣瀏覽器可以直接訪問根路徑,列出文件列表,和Ftp效果類似
autoindex_exact_size on; 顯示出文件的確切大小,單位是bytes。
改為off后,顯示出文件的大概大小,單位是kB或者M(jìn)B或者GB
autoindex_localtime on;
默認(rèn)為off,顯示的文件時(shí)間為GMT時(shí)間。
改為on后,顯示的文件時(shí)間為文件的服務(wù)器時(shí)間
3. 實(shí)例【靜態(tài)資源–圖片】,并開啟路徑目錄列表:
1. 在/home/nginx-1.22.0文件夾下創(chuàng)建images文件夾[可隨意路徑],放入圖片: MyIndex.jpg
2. 修改nginx.conf配置文件【路徑千萬(wàn)別找錯(cuò)了】
如 路徑: /usr/local/nginx/conf/nginx.conf 或 D:/images/;
3. 新增一個(gè)圖片資源路徑訪問location:
location /images {
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
alias /home/nginx-1.22.0/images/; # 最后的" / " 不能缺少
# alias F:\\PHP\\upload;
}
4. location中的root和alias參數(shù)說明:
alias和root區(qū)別:
1)alias指定的目錄是準(zhǔn)確的,Nginx訪問該location時(shí),資源路徑即alias指定的跟路徑;
2)root指定的目錄是location匹配訪問的path目錄的上一級(jí)目錄
# 如 location /imgs/, root配置為 /code/front/dist
# 那么,文件的路徑存在在: /code/front/dist/imgs/
3)使用alias標(biāo)簽的目錄塊中不能使用rewrite的break(具體原因不明);
另外,alias指定的目錄后面必須要加上 “ / ” 符號(hào)?。?!
4)root目錄配置中,location匹配的path目錄后面帶不帶"/",都不會(huì)影響訪問。
所以,一般情況下,在nginx配置中的良好習(xí)慣是:
1)在location /中配置root目錄;
2)在location /path中配置alias虛擬目錄。
# 假設(shè)項(xiàng)目文件夾:code , 靜態(tài)文件的位置:/code/front/dist/
# 如下使用root配置,會(huì)訪問不到,報(bào)404之類的:
location ^~ /static/ {
# 這里使用root的話,相當(dāng)于 文件的路徑為 /data/zfy_home/code/front/dist/static/
# root配置無(wú)效
root /data/zfy_home/code/front/dist/;
# 有效配置:
alias /data/zfy_home/code/front/dist/; # 使用alias時(shí), 最后的" / " 不能缺少
}
Or
location / {
# 這里直接使用root配置全路徑即可
# root配置有效
root /data/zfy_home/code/front/dist/;
# location后跟" / "時(shí),建議直接使用root了,alias多此一舉了感覺
alias /data/zfy_home/code/front/dist/; # 使用alias時(shí), 最后的" / " 不能缺少
}
文章來源:http://www.zghlxwxcb.cn/news/detail-698648.html
到了這里,關(guān)于Nginx訪問靜態(tài)資源配置的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!