Nginx配置location與rewrite規則教程

location教程

 

示例:php

location = / {
     # 精確匹配 /,主機名後面不能帶任何字符串
     [ configuration A ]  
}

location / {
     # 由於全部的地址都以/開頭,全部這條規則將匹配到全部請求
     # 可是正則和最長字符串會優先匹配
     [ configuration B ]
}

location /documents/ {
     # 匹配任何以/documents/開頭的地址,匹配符合之後,還要繼續往下搜索
     # 只有後面的正則表達式沒有匹配到時,這一條纔會採用
     [ configuration C ]
}

location ~ /documents/Abc {
     # 匹配任何以 /documents/開頭的地址,匹配符合之後,還要繼續往下搜索
     # 只有後面的正則表達式沒有匹配到時,纔會採用這一條  
     [ 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以某個常規字符串開頭,不是正則匹配
  • ~開頭表示區分大小寫的正則匹配
  • ~*開頭表示不區分大小寫的正則匹配
  • /通用匹配,若是沒有其它匹配,任何請求都會匹配到

順序 && 優先級css

(location =)> (location 完整路徑) > (location ^~路徑) > (location ~,~*正則順序) > (location 部分起始路徑) > (/)html

實際使用建議

#至少有三個匹配規則定義,以下:nginx

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

#直接轉發給後端應用服務器,也能夠是一個靜態首頁正則表達式

# 第一個必選規則後端

location = / {
     proxy_pass http://tomcat:8080/index
}

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

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

location ^~ /static/ {
     root /webroot/static/;
}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
     root /webroot/res/;
}

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

location / {
     proxy_pass http://tomcat:8080/
}

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到其餘機器。

執行順序:

  • server塊的rewrite指令
  • location匹配
  • 選定location中的rewrite指令,若是其中某步url被重寫,則重寫循環執行1-3,直到找到真是存在的文件;循環超過10次,則返回500 Internal Server Error錯誤

flag標誌位

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

由於301和302不能簡單的只返回狀態碼,還必須有重定向的URL,這就是return指令沒法返回301,302的緣由

last和break的異同:

  • last通常寫在server和if中,而break通常使用在location中
  • last不終止重寫後的url匹配,即新的url會再從server走一遍匹配流程,而break終止重寫後的匹配
  • break和last都能組織繼續執行後面的rewrite指令
if指令與全局變量
if判斷指令

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

當表達式只是一個變量時,若是值爲空或任何以0開頭的字符串都會當作false

直接比較變量和內容是,使用=!=

~ 正則表達式匹配,~* 不區分大小寫的匹配,!~ 區分大小寫的不匹配

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

例如:

if ($http_user_agent ~ MSIE) {
     rewrite ^(.*)$ /msie/$1 break;
} #若是UA包含」MSIE「,rewrite請求到/msie/目錄下

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.01;
} #若是請求的文件名不存在,則反向代理到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 : 請求頭中的Conten-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指令與URL請求生成
  • $scheme:HTTP方法(如http,https)
  • $server_protocol:請求使用的協議,一般是HTTP/1.0或HTTP/1.1
  • $server_addr:服務器地址,在完成一次系統調用後能夠肯定這個值
  • $server_name:服務器名稱
  • $server_port:請求到達服務器的端口號
  • $request_url:包含請求參數的原始url,不包含主機名,如「/foo/bar.php?arg=baz」
  • $url:不帶請求參數的當前url,$url不包含主機名,如「/foo/bar.html」
  • $document_url:與$url相同

示例:http://localhost:88/test1/test2/test.php

$host:localhost

$server_port:88

$request_url:http://localhost:88/test1/test2/test.php

$document_url:/test1/test2/test.php

$document_root:/var/www/html

$request_filename:/var/www/html/test1/test2/test.php

經常使用正則

  • .:匹配除換行符之外的任意字符
  • ?:重複0次或1次
  • +:重複1次或更屢次
  • *:重複1次或更屢次
  • \d:匹配數字
  • ^:匹配字符串的開始
  • $:匹配字符的結尾
  • {n}:重複n次
  • {n,}:重複n次或更屢次
  • [c]:匹配單個字符c
  • [a-z]:匹配a-z小寫字母的任意一個小括號()之間匹配的內容,能夠再後面經過$1來引用,$2表示的前面第二個()裏的內容。正則中容易讓人困惑的是\轉義特殊字符
rewrite實例

例1:

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 main;
                   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:

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

相關文章
相關標籤/搜索