Nginx——文件路徑配置


文件路徑的定義

以root方式設置資源路徑

語法:root path;

默認:root html;

配置塊:http、server、location、if

  location /data/ {
        root /web/html;
   }

如果請求的URI是/data/index/test.html,那么web服務器將返回/web/html/data/index/test.html文件的內容

alias設置資源路徑別名

語法:alias  path;

配置塊:location

    location /i/ {
        alias /data/w3/images/;
    }

如果一個請求的URI為 " /i/top.gif ",而實際想訪問的是 /data/w3/images/top.gif,就可以使用上面的配置

如果用root的方式來設置,需要配置成如下語句:

    location conf {
        root /usr/local/nginx/;
    }

可以理解為alias就相當於一個軟連接,匹配的時候location設置的路徑將被丟棄。而root則是根據URI路徑做映射。

alias后可以跟正則表達式:如

    location ~ ^/test/(\w+)\.(\w+)$ {
        alias usrlocal/nginx/$2/$1.$2;
    }    

首頁設置

語法:index file...;

默認:index index.html;

配置塊:http、server、location

index使用ngx_http_index_module模塊實現。index后可以跟多個文件參數,這些文件將按順序匹配。

    location  {
        root path;
        index index.html htmlindex.php /index.php;
    }    

這時,nginx首先嘗試訪問 path/index.php,如果可以訪問就直接返回,否則,再試圖訪問 path/htmlindex.php

根據HTTP返回碼重定向錯誤頁面

語法:error_page code[code...][=|=answer-code]uri|@named_location
配置塊:HTTP、server、location、if

如果請求返回錯誤碼,並且匹配了error_page中設置的code,將重定向到指定的URI中。

error_page 404 404.html;
error_page 502 503 504 50x.html;
error_page 403 http://example.com/forbidden.html;
error_page 404 = @fetch;

注意:雖然重定向了URI,但返回碼還是原來的HTTP_CODE。可以通過 "=" 更改返回的錯誤碼。如

error_page 404 =200 empty.gif;
error_page 404 =403 forbidden.gif;

也可以不指定確切的錯誤碼,而是由重定向后實際處理的真實結果來決定, 只要把 “=”后面的錯誤碼換成路徑即可,如

error_page 404 = /empty.gif;

如果不想修改URI,只是想讓請求重定向到location中處理,如

    location / {
        error_page 404 @fallback;
    }
    location @fallback {
        proxy_pass http://backend;
    }    

這樣, 返回404的請求會被反向代理到http://backend 上游服務器中處理

try_files

語法:try_files path1 [path2] uri;
     try_files file ... =code;

配置塊:server、location

try_files后要跟若干路徑, 如path1 path2..., 而且最后必須要有uri參數,

意義如下:嘗試按照順序訪問每一個path, 如果可以有效地讀取, 就直接向用戶返回這個path對應的文件結束請求, 否則繼續向下訪問。

如果所有的path都找不到有效的文件, 就重定向到最后的參數uri上。 因此, 最后這個參數uri必須存在, 而且它應該是可以有效重定向的。 例如:

location /images/ {
    try_files $uri $uri/ /images/default.gif;     #$uri表示文件,$uri/表示目錄
} 
location
= /images/default.gif {
  expires 30s;
}

 

如果請求是 uri為/images/abc,

try_files 會先判斷請求的是文件還是目錄。如果是文件,那么與$uri匹配,找 /images下是否有這個abc文件,如果有就直接返回,如果沒有就找第二個參數$uri/,找不到的時候用最后一個參數/images/default.gif處理

 

    try_files systemmaintenance.html $uri $uri/index.html $uri.html @other;
    location @other {
        proxy_pass http://backend;
    }

表示如果前面的路徑都匹配不到,就反向代理至http://backend服務器上

try_files與rewrite的結合

  location  / {
                root  /var/www/build;
                index  index.html index.htm;
                try_files $uri $uri/ @rewrites;
        }
  
location @rewrites {
             rewrite ^(.+)$ /index.html last;
        }

也可以指定錯誤碼和error_page配合使用,如

    location {
        try_files $uri $uri /error.phpc=404 =404;
    }


免責聲明!

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



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