1. 程式人生 > >nginx location配置及解析過程

nginx location配置及解析過程

location 語法

location 有”定位”的意思, 根據Uri來進行不同的定位.

在虛擬主機的配置中,是必不可少的,location可以把網站的不同部分,定位到不同的處理方式上.

比如, 碰到.php, 如何呼叫PHP直譯器?  --這時就需要location

location 的語法

location [=|~|~*|^~] patt {

}

中括號可以不寫任何引數,此時稱為一般匹配

也可以寫引數

因此,大型別可以分為3種

location = patt {} [精準匹配]

location patt{}  [一般匹配]

location ~ patt{} [正則匹配]

如何發揮作用?:

首先看有沒有精準匹配,如果有,則停止匹配過程.

location = patt {

   config A

}

如果 $uri ==patt,匹配成功,使用configA

  location = / {

              root   /var/www/html/;

            index  index.htm index.html;

       }

 location / {

            root   /usr/local/nginx/html;

           index  index.html index.htm;

  }

定位流程是 

1: 精準匹配中 ”/”   ,得到index頁為  index.htm

2: 再次訪問 /index.htm , 此次內部轉跳uri已經是”/index.htm” ,

根目錄為/usr/local/nginx/html

3: 最終結果,訪問了/usr/local/nginx/html/index.htm

再來看,正則也來參與.

location / {

            root   /usr/local/nginx/html;

            index  index.html index.htm;

        }

location ~ image {

           root /var/www/image;

           index index.html;

}

此時, “/” 與”/image/logo.png”匹配

同時,”image”正則 與”image/logo.png”也能匹配,誰發揮作用?

正則表示式的成果將會使用.

圖片真正會訪問 /var/www/image/logo.png 

location / {

            root   /usr/local/nginx/html;

            index  index.html index.htm;

        }

location /foo {

           root /var/www/html;

            index index.html;

}

我們訪問http://xxx.com/foo

 對於uri “/foo”,   兩個location的patt,都能匹配他們

即 ‘/’能從左字首匹配 ‘/foo’, ‘/foo’也能左字首匹配’/foo’,

此時, 真正訪問 /var/www/html/index.html

原因:’/foo’匹配的更長,因此使用之.;