Linux:nginx alias和root處理靜態資源區別

nginx指定文件路徑有兩種方式:alias和root;

使用方法和作用域如下:

【root】
語法      root path;
默認值    root html; #代表nginx目錄下html文件夾
作用域    http、server、location、if

【alias】
語法      alias path; #path結尾一定要加以“/”結束
作用域    location

root和aligs區別:

1)alias指定的目錄是準確的,location替換爲aligs路徑,即location匹配到的path路徑下的文件在aligs目錄下是可以找到的;
2)root指定的目錄是location匹配訪問path路徑的上一級目錄,這個path目錄要真實存在在root路徑下;
3)使用alias的location代碼塊中,不能存在rewrite的break;alias路徑最後必須帶上“/”;
4)alias的location匹配的path路徑中,如果最後不加“/”,訪問的時候會自動加上“/”;如果path後面加上“/”,訪問的時候路徑最後必須加上“/”,否則會保存
5)root的location匹配的path路徑中,加不加“/”都可以

eg:假如訪問路徑都是http://www.test.com/test/aaa.html

eg1:

location /test/ {
    alias /home/test/;
}
訪問http://www.test.com/test/aaa.html 實際爲 /home/test/aaa.html

改爲root方式:
location /test/ {
    root /home/;
}
訪問http://www.test.com/test/aaa.html 實際爲 /home/test/aaa.html

.eg2:訪問路徑和文件路徑不一致

location /test/ {
    alias /home/web/;
}
訪問http://http://www.test.com/test/aaa.html 實際爲 /home/web/aaa.html

如果改爲root方式:
先通過軟連接,將/home/web/ 軟連接到/home/test/目錄
ln -s /home/test/ /home/web/
location /test/ {
    root /home;
}

建議:1.location / 使用root;2.location /path 使用alias;

如下:
server {
   listen 80;
   server_name www.test.com;
   index index.html index.php index.htm;
   access_log /usr/local/nginx/logs/image.log;

   location / {
        root /var/www/html;
   }

   location /haha {//匹配的path目錄haha不需要真實存在alias指定的目錄中
       alias   /var/www/html/ops/;//後面的"/"符號一定要帶上
       rewrite ^/opp/hen.php(.*)$ /opp/hen.php?s=$1 last;
       # rewrite ^/opp/(.*)$ /opp/hen.php?s=$1 last;
   }

   location /wang {//匹配的path目錄wang一定要真實存在root指定的目錄中(就/var/www/html下一定要有wang目錄存在)
      root /var/www/html;
   }

}

=============================再看下面一例=============================
[root@web01 vhosts]# cat www.kevin.com.conf
server {
  listen      80;
  server_name www.test.com;
     
  access_log  /data/nginx/logs/www.kevin.com-access.log main;
  error_log  /data/nginx/logs/www.kevin.com-error.log;
     
  location / {
      root /data/web/kevin;
      index index.php index.html index.htm;
  }
 
  location /document/ {
      alias /data/web/document/;
  }
 
}
 
 
[root@web01 vhosts]# ll /data/web/
total 4
drwxrwxr-x 2 app app   33 Nov 22 10:22 document
drwxrwxr-x 4 app app  173 Sep 23 15:00 kevin
 
如上配置後,則:
訪問http://www.kevin.com/admin   就會找到/data/web/kevin/admin目錄
訪問http://www.kevin.com/document  就會找到/data/web/document 目錄 (裏面是一些靜態資源)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章