nginx ----location、alias 、index


  location [ = | ~ | ~* | ^~ ] uri { ... }
  location @name { ... }
在一個server中location配置段可存在多個,用於實現從uri到文件系統的路徑映射;ngnix會根據用戶請求的URI來檢查定義的所有location,並找出一個最佳匹配,而后應用其配置

  定制訪問路徑:

 root /data/site1;

  一、修改配置文件

server { server_name www.a.net ;   root /data/site1; location /test {   root /opt/testdir; } }

默認訪問的路徑是:/data/下的site1文件夾

當訪問/test 的時候,訪問的是opt下的testdir 這個文件夾下的test文件

  二、創建對應的文件夾

mkdir /opt/testdir/test -pv

 echo /opt/testdir/test/index.html > /opt/testdir/test/index.html

  三、測試訪問

1 curl www.a.net/test/
2 /opt/testdir/test/index.html

  =   對URI做精確匹配;
    location = / {
      ...
  }
    http://www.magedu.com/ 匹配
    http://www.magedu.com/index.html 不匹配
  ^~   對URI的最左邊部分做匹配檢查,不區分字符大小寫
  ~   對URI做正則表達式模式匹配,區分字符大小寫
  ~*   對URI做正則表達式模式匹配,不區分字符大小寫
  不帶符號 匹配起始於此uri的所有的uri
  \   轉義符,可將 . * ?等轉義為普通符號
  匹配優先級從高到低:
    =, ^~, ~/~*, 不帶符號


 

alias 別名 嵌套在location中

  1、查看location配置

server { server_name www.a.net ;     root /data/site1; location /test {      root /opt/testdir; }  location /about { root /opt/testdir; } }

  2、測試訪問

1 curl 192.168.1.5/about/
2 /opt/testdir/about/index.html

root訪問的是192.168.1.5/opt/testdir/about/index.html會在testdir下面補一個about路徑

  3、修改為alias

server { server_name www.a.net ; root /data/site1; location /test { root /opt/testdir; }  location /about { alias /opt/testdir; } }

  4、測試訪問

1 curl 192.168.1.5/about/
2 /opt/testdir/index.html

alias是當訪問192.168.1.5下的about文件,實際訪問的是/opt/testdir/下的index.html

 location /test 后不要加斜線,千萬不要寫成location /test/否則會出現很多問題!!!
使用alias的時候,url后面如果加了斜杠,則下面的路徑必須也加斜杠,否則403
演示:

1、都不加斜杠,正常訪問
curl 192.168.1.5/about/
/opt/testdir/index.html
 
        

2、uri后面添加了斜杠,但路徑沒加

 
        
server { server_name www.a.net ; root /data/site1; location /test { root /opt/testdir; }  location /about/ { alias /opt/testdir; } }
測試訪問
curl 192.168.1.5/about/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

3、url加了斜杠,路徑也加了斜杠

server { server_name www.a.net ; root /data/site1; location /test { root /opt/testdir; }  location /about/ { alias /opt/testdir/; } }

測試訪問,一切正常

curl 192.168.1.5/about/
/opt/testdir/index.html

index file ...;
指定默認網頁文件,此指令由ngx_http_index_module模塊提供

指定test.index 才是主頁 

1、指定當訪問www.a.net的about的時候訪問的是/opt下的testdir下的test.html頁面

server {
        server_name www.a.net;
        root /data/site1;
        location /about { root /opt/testdir/; index test.html;
        }
        error_page 404 /404.html;
        location = /404.html {
        }
}
~            
2、新建測試頁面
echo /opt/testdir/about/test.html > /opt/testdir/about/test.html 

3、測試訪問,加-L

curl www.a.net/about -L
/opt/testdir/about/test.html

-L 跟蹤重定向,否則通過curl命令只能看到重定向頁面


 


免責聲明!

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



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