nginx配置location總結及rewrite規則寫法

1. location正則寫法

一個示例:php

 

1css

2html

3nginx

4web

5正則表達式

6後端

7tomcat

8服務器

9cookie

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

 

location = / {

# 精確匹配 / ,主機名後面不能帶任何字符串

[ configuration A ]

}

location / {

# 由於全部的地址都以 / 開頭,因此這條規則將匹配到全部請求

# 可是正則和最長字符串會優先匹配

[ configuration B ]

}

location /documents/ {

# 匹配任何以 /documents/ 開頭的地址,匹配符合之後,還要繼續往下搜索

# 只有後面的正則表達式沒有匹配到時,這一條纔會採用這一條

[ configuration C ]

}

location ~ /documents/Abc {

# 匹配任何以 /documents/Abc 開頭的地址,匹配符合之後,還要繼續往下搜索

# 只有後面的正則表達式沒有匹配到時,這一條纔會採用這一條

[ configuration CC ]

}

location ^~ /images/ {

# 匹配任何以 /images/ 開頭的地址,匹配符合之後,中止往下搜索正則,採用這一條。

[ configuration D ]

}

location ~* \.(gif|jpg|jpeg)$ {

# 匹配全部以 gif,jpg或jpeg 結尾的請求

# 然而,全部請求 /images/ 下的圖片會被 config D 處理,由於 ^~ 到達不了這一條正則

[ configuration E ]

}

location /images/ {

# 字符匹配到 /images/,繼續往下,會發現 ^~ 存在

[ configuration F ]

}

location /images/abc {

# 最長字符匹配到 /images/abc,繼續往下,會發現 ^~ 存在

# F與G的放置順序是沒有關係的

[ configuration G ]

}

location ~ /images/abc/ {

# 只有去掉 config D 纔有效:先最長匹配 config G 開頭的地址,繼續往下搜索,匹配到這一條正則,採用

[ configuration H ]

}

location ~* /js/.*/\.js

  • =開頭表示精確匹配
    如 A 中只匹配根目錄結尾的請求,後面不能帶任何字符串。
  • ^~ 開頭表示uri以某個常規字符串開頭,不是正則匹配
  • ~ 開頭表示區分大小寫的正則匹配;
  • ~* 開頭表示不區分大小寫的正則匹配
  • / 通用匹配, 若是沒有其它匹配,任何請求都會匹配到

順序 no優先級:
(location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)

上面的匹配結果
按照上面的location寫法,如下的匹配示例成立:

  • / -> config A
    精確徹底匹配,即便/index.html也匹配不了
  • /downloads/download.html -> config B
    匹配B之後,往下沒有任何匹配,採用B
  • /images/1.gif -> configuration D
    匹配到F,往下匹配到D,中止往下
  • /images/abc/def -> config D
    最長匹配到G,往下匹配D,中止往下
    你能夠看到 任何以/images/開頭的都會匹配到D並中止,FG寫在這裏是沒有任何意義的,H是永遠輪不到的,這裏只是爲了說明匹配順序
  • /documents/document.html -> config C
    匹配到C,往下沒有任何匹配,採用C
  • /documents/1.jpg -> configuration E
    匹配到C,往下正則匹配到E
  • /documents/Abc.jpg -> config CC
    最長匹配到C,往下正則順序匹配到CC,不會往下到E

實際使用建議

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

 

因此實際使用中,我的以爲至少有三個匹配規則定義,以下:

#直接匹配網站根,經過域名訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。

#這裏是直接轉發給後端應用服務器了,也能夠是一個靜態首頁

# 第一個必選規則

location = / {

proxy_pass http://tomcat:8080/index

}

# 第二個必選規則是處理靜態文件請求,這是nginx做爲http服務器的強項

# 有兩種配置模式,目錄匹配或後綴匹配,任選其一或搭配使用

location ^~ /static/ {

root /webroot/static/;

}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {

root /webroot/res/;

}

#第三個規則就是通用規則,用來轉發動態請求到後端應用服務器

#非靜態文件請求就默認是動態請求,本身根據實際把握

#畢竟目前的一些框架的流行,帶.php,.jsp後綴的狀況不多了

location / {

proxy_pass http://tomcat:8080/

}

http://tengine.taobao.org/book/chapter_02.html
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

2. Rewrite規則

rewrite功能就是,使用nginx提供的全局變量或本身設置的變量,結合正則表達式和標誌位實現url重寫以及重定向。rewrite只能放在server{},location{},if{}中,而且只能對域名後邊的除去傳遞的參數外的字符串起做用,例如 http://seanlook.com/a/we/index.php?id=1&u=str 只對/a/we/index.php重寫。語法rewrite regex replacement [flag];

若是相對域名或參數字符串起做用,可使用全局變量匹配,也可使用proxy_pass反向代理。

代表看rewrite和location功能有點像,都能實現跳轉,主要區別在於rewrite是在同一域名內更改獲取資源的路徑,而location是對一類路徑作控制訪問或反向代理,能夠proxy_pass到其餘機器。不少狀況下rewrite也會寫在location裏,它們的執行順序是:

  1. 執行server塊的rewrite指令
  2. 執行location匹配
  3. 執行選定的location中的rewrite指令

若是其中某步URI被重寫,則從新循環執行1-3,直到找到真實存在的文件;循環超過10次,則返回500 Internal Server Error錯誤。

2.1 flag標誌位

  • last : 至關於Apache的[L]標記,表示完成rewrite
  • break : 中止執行當前虛擬主機的後續rewrite指令集
  • redirect : 返回302臨時重定向,地址欄會顯示跳轉後的地址
  • permanent : 返回301永久重定向,地址欄會顯示跳轉後的地址

由於301和302不能簡單的只返回狀態碼,還必須有重定向的URL,這就是return指令沒法返回301,302的緣由了。這裏 last 和 break 區別有點難以理解:

  1. last通常寫在server和if中,而break通常使用在location中
  2. last不終止重寫後的url匹配,即新的url會再從server走一遍匹配流程,而break終止重寫後的匹配
  3. break和last都能組織繼續執行後面的rewrite指令

2.2 if指令與全局變量

if判斷指令
語法爲if(condition){...},對給定的條件condition進行判斷。若是爲真,大括號內的rewrite指令將被執行,if條件(conditon)能夠是以下任何內容:

  • 當表達式只是一個變量時,若是值爲空或任何以0開頭的字符串都會當作false
  • 直接比較變量和內容時,使用=!=
  • ~正則表達式匹配,~*不區分大小寫的匹配,!~區分大小寫的不匹配

-f!-f用來判斷是否存在文件
-d!-d用來判斷是否存在目錄
-e!-e用來判斷是否存在文件或目錄
-x!-x用來判斷文件是否可執行

例如:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

 

if ($http_user_agent ~ MSIE) {

rewrite ^(.*)$ /msie/$1 break;

} //若是UA包含"MSIE",rewrite請求到/msid/目錄下

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {

set $id $1;

} //若是cookie匹配正則,設置變量$id等於正則引用部分

if ($request_method = POST) {

return 405;

} //若是提交方法爲POST,則返回狀態405(Method not allowed)。return不能返回301,302

if ($slow) {

limit_rate 10k;

} //限速,$slow能夠經過 set 指令設置

if (!-f $request_filename){

break;

proxy_pass http://127.0.0.1;

} //若是請求的文件名不存在,則反向代理到localhost 。這裏的break也是中止rewrite檢查

if ($args ~ post=140){

rewrite ^ http://example.com/ permanent;

} //若是query string中包含"post=140",永久重定向到example.com

location ~* \.(gif|jpg|png|swf|flv)$ {

valid_referers none blocked www.jefflei.com www.leizhenfang.com;

if ($invalid_referer) {

return 404;

} //防盜鏈

}

 

全局變量
下面是能夠用做if判斷的全局變量

  • $args : #這個變量等於請求行中的參數,同$query_string
  • $content_length : 請求頭中的Content-length字段。
  • $content_type : 請求頭中的Content-Type字段。
  • $document_root : 當前請求在root指令中指定的值。
  • $host : 請求主機頭字段,不然爲服務器名稱。
  • $http_user_agent : 客戶端agent信息
  • $http_cookie : 客戶端cookie信息
  • $limit_rate : 這個變量能夠限制鏈接速率。
  • $request_method : 客戶端請求的動做,一般爲GET或POST。
  • $remote_addr : 客戶端的IP地址。
  • $remote_port : 客戶端的端口。
  • $remote_user : 已經通過Auth Basic Module驗證的用戶名。
  • $request_filename : 當前請求的文件路徑,由root或alias指令與URI請求生成。
  • $scheme : HTTP方法(如http,https)。
  • $server_protocol : 請求使用的協議,一般是HTTP/1.0或HTTP/1.1。
  • $server_addr : 服務器地址,在完成一次系統調用後能夠肯定這個值。
  • $server_name : 服務器名稱。
  • $server_port : 請求到達服務器的端口號。
  • $request_uri : 包含請求參數的原始URI,不包含主機名,如:」/foo/bar.php?arg=baz」。
  • $uri : 不帶請求參數的當前URI,$uri不包含主機名,如」/foo/bar.html」。
  • $document_uri : 與$uri相同。

例:http://localhost:88/test1/test2/test.php
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

2.3 經常使用正則

  • . : 匹配除換行符之外的任意字符
  • ? : 重複0次或1次
  • + : 重複1次或更屢次
  • * : 重複0次或更屢次
  • \d :匹配數字
  • ^ : 匹配字符串的開始
  • $ : 匹配字符串的介紹
  • {n} : 重複n次
  • {n,} : 重複n次或更屢次
  • [c] : 匹配單個字符c
  • [a-z] : 匹配a-z小寫字母的任意一個

小括號()之間匹配的內容,能夠在後面經過$1來引用,$2表示的是前面第二個()裏的內容。正則裏面容易讓人困惑的是\轉義特殊字符。

2.4 rewrite實例

例1

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

 

http {

# 定義image日誌格式

log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;

# 開啓重寫日誌

rewrite_log on;

server {

root /home/www;

location / {

# 重寫規則信息

error_log logs/rewrite.log notice;

# 注意這裏要用‘’單引號引發來,避免{}

rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;

# 注意不能在上面這條規則後面加上「last」參數,不然下面的set指令不會執行

set $image_file $3;

set $image_type $4;

}

location /data {

# 指定針對圖片的日誌格式,來分析圖片類型和大小

access_log logs/images.log mian;

root /data/images;

# 應用前面定義的變量。判斷首先文件在不在,不在再判斷目錄在不在,若是還不在就跳轉到最後一個url裏

try_files /$arg_file /image404.html;

}

location = /image404.html {

# 圖片不存在返回特定的信息

return 404 "image not found\n";

}

}

 

對形如/images/ef/uh7b3/test.png的請求,重寫到/data?file=test.png,因而匹配到location /data,先看/data/images/test.png文件存不存在,若是存在則正常響應,若是不存在則重寫tryfiles到新的image404 location,直接返回404狀態碼。

例2

 

1

 

rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;

 

對形如/images/bla_500x400.jpg的文件請求,重寫到/resizer/bla.jpg?width=500&height=400地址,並會繼續嘗試匹配location。

例3
見 ssl部分頁面加密 。

相關文章
相關標籤/搜索