參考來源: http://blog.zol.com.cn/1067/article_1066186.html,http://flandycheng.blog.51cto.com/855176/280121
語法規則: location [=|~|~*|^~] /uri/ { … }
= 開頭表示精確匹配
^~ 開頭表示uri以某個常規字符串開頭,理解爲匹配 url路徑即可。nginx不對url做編碼,因此請求爲/static/20%/aa,可以被規則^~ /static/ /aa匹配到(注意是空格)。
~ 開頭表示區分大小寫的正則匹配
~* 開頭表示不區分大小寫的正則匹配
!~和!~*分別爲區分大小寫不匹配及不區分大小寫不匹配 的正則
/ 通用匹配,任何請求都會匹配到。
多個location配置的情況下匹配順序爲(參考資料而來,還未實際驗證,試試就知道了,不必拘泥,僅供參考):
首先匹配 =,其次匹配^~, 其次是按文件中順序的正則匹配,最後是交給 / 通用匹配。當有匹配成功時候,停止匹配,按當前匹配規則處理請求。
例子,有如下匹配規則:
那麼產生的效果如下:
訪問根目錄/, 比如http://localhost/ 將匹配規則A
訪問 http://localhost/login 將匹配規則B,http://localhost/register 則匹配規則H
訪問 http://localhost/static/a.html 將匹配規則C
訪問 http://localhost/a.gif, http://localhost/b.jpg 將匹配規則D和規則E,但是規則D順序優先,規則E不起作用, 而 http://localhost/static/c.png 則優先匹配到 規則C
訪問 http://localhost/a.PNG 則匹配規則E, 而不會匹配規則D,因爲規則E不區分大小寫。
訪問 http://localhost/a.xhtml 不會匹配規則F和規則G,http://localhost/a.XHTML不會匹配規則G,因爲不區分大小寫。規則F,規則G屬於排除法,符合匹配規則但是不會匹配到,所以想想看實際應用中哪裏會用到。
訪問 http://localhost/category/id/1111 則最終匹配到規則H,因爲以上規則都不匹配,這個時候應該是nginx轉發請求給後端應用服務器,比如FastCGI(php),tomcat(jsp),nginx作爲方向代理服務器存在。
所以實際使用中,個人覺得至少有三個匹配規則定義,如下:
對於以上基礎推薦配置,有一個補充,就是關於轉發有一點需要注意。例如下面配置,對一個目錄轉發:
location ^~/outer/{
#case A: url最後以/結尾
proxy_pass http://tomcat:8080/
#case B: url最後沒有/
#proxy_pass http://tomcat:8080
}
關鍵在於最後的/,訪問localhost/outer/in.html,其中case A 會轉發到tomcat:8080/in.html, 而case B 會轉發到 tomcat:8080/outer/in.html,所以務必注意了。
未試驗過的其他信息:
三、ReWrite語法
last – 基本上都用這個Flag。
break – 中止Rewirte,不在繼續匹配
redirect – 返回臨時重定向的HTTP狀態302
permanent – 返回永久重定向的HTTP狀態301
1、下面是可以用來判斷的表達式:
-f和!-f用來判斷是否存在文件
-d和!-d用來判斷是否存在目錄
-e和!-e用來判斷是否存在文件或目錄
-x和!-x用來判斷文件是否可執行
2、下面是可以用作判斷的全局變量
例: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:D:\nginx/html
$request_filename:D:\nginx/html/test1/test2/test.php
四、Redirect語法
server {
listen 80;
server_name start.igrow.cn;
index index.html index.php;
root html;
if ($http_host !~ “^star\.igrow\.cn$" {
rewrite ^(.*) http://star.igrow.cn$1 redirect;
}
}
五、防盜鏈location ~* \.(gif|jpg|swf)$ {
valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid_referer) {
rewrite ^/ http://$host/logo.png;
}
}
六、根據文件類型設置過期時間
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
expires 1h;
break;
}
}
七、禁止訪問某個目錄
location ~* \.(txt|doc)${
root /data/www/wwwroot/linuxtone/test;
deny all;
}
++ 一些可用的全局變量
$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri