Nginx 正則匹配


Nginx 正則表達式之匹配操作符

~     區分大小寫(大小寫敏感)匹配成功 
~*   不區分大小寫匹配成功 
!~    區分大小寫匹配失敗 
!~*  不區分大小寫匹配失敗
^      以什么開頭的匹配
$      以什么結尾的匹配
*      代表任意字符

過期緩存

expires      30d;

表示過期時間30天

針對瀏覽器

location / {
    if ($http_user_agent ~* chrome) {
        return 503;
    }
}

禁止訪問Chrome瀏覽器。

針對文件類型

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
	expires      30d;
}

針對文件夾

location /test/ {
	return 403;
}

判斷文件,文件夾

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

設置某些類型文件的瀏覽器緩存時間

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
    expires 30d;
}
location ~ .*\.(js|css)$
{
    expires 1h;
}

匹配到所有uri

location / {
    
}

last一般寫在server和if中,而break一般使用在location中。

redirect : 返回302臨時重定向,地址欄會顯示跳轉后的地址。

全局變量

$args                                         請求中的參數,如www.abc.com/test/hello?a=1&b=2的$args就是a=1&b=2
$document_root		          Nginx虛擬主機配置文件中的root參數對應的值
$document_uri			  當前請求中不包含指令的URI,如www.abc.com/test/hello?a=1&b=2的document_uri就是/test/hello,不包含后面的參數
$host					  主機頭,也就是域名
$http_user_agent                      客戶端的詳細信息,也就是瀏覽器的標識,用curl -A可以指定
$http_cookie			   	  客戶端的cookie信息
$limit_rate				  如果Nginx服務器使用limit_rate配置了顯示網絡速率,則會顯示,如果沒有設置,則顯示0
$remote_addr  			  客戶端的公網IP
$remote_port			          客戶端的端口
$request_method		          請求資源的方式,GET/PUT/DELETE等
$request_filename	                  當前請求的資源文件的路徑名稱,相當於是$document_root/$document_uri的組合
$request_uri				  請求的鏈接,包括$document_uri和$args
$scheme					  請求的協議,如ftp、http、https
$server_protocol		          客戶端請求資源使用的協議的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等
$server_addr				  服務器IP地址
$server_name			          服務器的主機名 			
$server_port 				  服務器的端口號
$uri						  和$document_uri相同
$http_referer				  客戶端請求時的referer,通俗講就是該請求是通過哪個鏈接跳過來的

常用:$http_referer	
     $request_uri  
     $http_user_agent  

案例

args:name=zhangsan&age=15
document_root:/home/wwwroot/default/wounion/dragonfly/public
document_uri:/test/hello
host:jiqing.wounion.com
http_user_agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36
http_cookie:PHPSESSID=3ire1fr9bl3qdpd787pv0qb7a5
limit_rate:0
remote_addr:127.0.0.1
remote_port:43180
request_method:GET
request_filename:/home/wwwroot/default/wounion/dragonfly/public/test/hello
request_uri:/test/hello?name=zhangsan&age=15
scheme:http
server_protocol:HTTP/1.1
server_addr:127.0.0.1
server_name:jiqing.wounion.com
server_port:80
uri:/test/hello
http_referer:


常用正則

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM