如果希望域名后邊跟隨的路徑指向本地磁盤的其他目錄,而不是默認的web目錄時,需要設置nginx目錄訪問重定向. 應用場景:dashidan.com/image自動跳轉到dashidan.com/folderName/image.nginx目錄路徑重定向的四種實現方式.修改root映射,通過Nginx rewrite內部跳轉,設置別名alias映射實現,通過nginx的permanent 301絕對跳轉實現.
1 nginx修改root映射
修改root映射實現nginx目錄訪問重定向是最簡單的方式, 推薦采用這一種.
1
2
3
|
location /image { root /folderName ; } |
2 通過nginx rewrite內部跳轉實現訪問重定向
nginx配置代碼示例:
1
2
3
|
location /image { rewrite ^ /image/ (.*)$ /folderName/image/ $1 last; } |
3 nginx設置別名alias映射實現
配置示例:
1
2
3
|
location /image { alias /folderName/image ; #這里寫絕對路徑 } |
4 通過nginx的permanent 301絕對跳轉實現
配置示例:
1
2
3
|
location /image { rewrite ^ /image/ (.*)$ http: //dashidan .com /folderName/image/ $1; } |
5 通過判斷uri實現頁面跳轉
配置示例:
1
2
3
|
if ( $request_uri ~* ^( /image )){ rewrite ^ /image/ (.*)$ /folderName/image/ $1 last; } |
nginx location匹配規則
location匹配命令
~ #波浪線表示執行一個正則匹配,區分大小寫
~* #表示執行一個正則匹配,不區分大小寫
^~ #^~表示普通字符匹配,如果該選項匹配,只匹配該選項,不匹配別的選項,一般用來匹配目錄
= #進行普通字符精確匹配
@ #"@" 定義一個命名的 location,使用在內部定向時,例如 error_page, try_files
- =前綴的指令嚴格匹配這個查詢。如果找到,停止搜索。
- 所有剩下的常規字符串,最長的匹配。如果這個匹配使用^?前綴,搜索停止。
- 正則表達式,在配置文件中定義的順序。
- 如果第3條規則產生匹配的話,結果被使用。否則,如同從第2條規則被使用。
location 匹配的優先級(與location在配置文件中的順序無關)
= 精確匹配會第一個被處理。如果發現精確匹配,nginx停止搜索其他匹配。
普通字符匹配,正則表達式規則和長的塊規則將被優先和查詢匹配,也就是說如果該項匹配還需去看有沒有正則表達式匹配和更長的匹配。
^~ 則只匹配該規則,nginx停止搜索其他匹配,否則nginx會繼續處理其他location指令。
最后匹配理帶有"~"和"~*"的指令,如果找到相應的匹配,則nginx停止搜索其他匹配;當沒有正則表達式或者沒有正則表達式被匹配的情況下,那么匹配程度最高的逐字匹配指令會被使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
location = / { # 只匹配"/". [ configuration A ] } location / { # 匹配任何請求,因為所有請求都是以"/"開始 # 但是更長字符匹配或者正則表達式匹配會優先匹配 [ configuration B ] } location ^~ /images/ { # 匹配任何以 /images/ 開始的請求,并停止匹配 其它location [ configuration C ] } location ~* \.(gif|jpg|jpeg)$ { # 匹配以 gif, jpg, or jpeg結尾的請求. # 但是所有 /images/ 目錄的請求將由 [Configuration C]處理. [ configuration D ] } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/sinbadfreedom/article/details/79494702