經過官方文檔能夠看到,rewrite的做用上下文是 server location,能夠寫在 server裏面 亦或location裏面;html
命令:nginx
if (條件) {} 條件判斷 set #設置變量 return #返回狀態碼 break #跳出rewrite rewrite #重寫
條件:服務器
= 字符串比較 ~ 區分大小寫正則 ~* 不區分大小寫正則 -f 是否爲文件 -d 是否爲目錄 -e 是否存在 ! 取反
例子:url
if ($requesy_method=POST) { return 405; } if ($http_user_agent ~ MSIE) { rewrite ^.*$ /ie.html; break;(若是不break,循環重定向) } 訪問一個不存在的頁面 /xxx.html if (!-e $document_root$fastcgi_script_name) { rewrite ^.*$ /404.html break ; # 晃眼一看以爲這個地方不必break了,實際上這個地方仍是要加 break,不然循環重定向,解釋: 服務器內部的rewrite和302跳轉不同,跳轉的話url都變了,變成從新http請求 404.html,而內部rewrite, 上下文沒有變,就是說 fastcgi_script_name 任然是 xxx.html,所以 會循環重定向 } 若是是經過apt方式安裝的nginx,可用的變量保存在 /etc/nginx/fastcgi_params set 舉例 if ( $http_user_agent ~* msie ) { set $isie 1; } if ( $fastcgi_script_name = ie.html ) { set $isie 0; } if ( $isie 1 ) { rewrite ^.*$ ie.html; }