天天看點

nginx配置location使用建議及rewrite規則

location實際使用建議

是以實際使用中,個人覺得至少有三個比對規則定義,如下:
#直接比對網站根,通過域名通路網站首頁比較頻繁,使用這個會加速處理,官網如是說。
#這裡是直接轉發給後端應用伺服器了,也可以是一個靜态首頁
# 第一個必選規則
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/
}
           

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錯誤。

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指令

nginx rewrite 指令last break差別

執行個體

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: 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。

全局變量 下面是可以用作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

轉載文章:https://segmentfault.com/a/1190000002797606

Java從背景重定向(redirect) 通過HttpServletResponse跳轉

@RequestMapping("alipayforward/{contNo}")  
public void alipayforward(@PathVariable("contNo") String contNo, HttpServletRequest req, HttpServletResponse resp) throws Exception {  
	//String contNo =req.getParameter("contNo"); //保單号  
	logger.info("通路/downloadRequestElecCont.action");  
	resp.sendRedirect("http://baidu.com/downloadRequestElecCont.action?contNo="+contNo);  
}  
           

繼續閱讀