Nginx 支持在if 语句中使用正则. 例如:
if ( condition ){ do_something } if ( $http_user_agent = "wget" ){ do_something } if ( $http_user_agent ~ MSIE ){ return 403; }
一些常用规则:
1) The comparison of variable with the line with using the = and != operators; 2) Pattern matching with regular expressions using the symbols ~* and ~:~ is case-sensitive match 3) ~* specifies a case-insensitive match (firefox matches FireFox) 4) ~ and !~* mean the opposite, “doesn’t match” 5) checking for the existence of a file using the -f and !-f operators; 6) checking existence of a directory using the -d and !-d operators; 7) checking existence of a file, directory or symbolic link using the -e and !-e operators; 8) checking whether a file is executable using the -x and !-x operators. 9) Parts of the regular expressions can be in parentheses, whose value can then later be accessed in the $1 to $9 variables
一般的使用建议是多用map,少用if
if ($http_user_agent ~ (iPhone|Android) ) { rewrite ^(.*) https://m.domain1.com$1 permanent; } if ($http_user_agent ~ (MSIE|Mozilla) ) { rewrite ^(.*) https://domain2.com$1 permanent; }
在nginx 0.9.6以后,支持使用map功能,上面的例子是配合map,可以改成
http { map $http_user_agent $ua_redirect { default ''; ~(iPhone|Android) m.domain1.com; ~(MSIE|Mozilla) domain2.com; } server { if ($ua_redirect != '') { rewrite ^ https://$ua_redirect$request_uri? permanent; } } }
另外一个例子:
### Testing if the client is a mobile or a desktop. ### The selection is based on the usual UA strings for desktop browsers. ## Testing a user agent using a method that reverts the logic of the ## UA detection. Inspired by notnotmobile.appspot.com. map $http_user_agent $is_desktop { default 0; ~*linux.*android|windows\s+(?:ce|phone) 0; # exceptions to the rule ~*spider|crawl|slurp|bot 1; # bots ~*windows|linux|os\s+x\s*[\d\._]+|solaris|bsd 1; # OSes } ## Revert the logic. map $is_desktop $is_mobile { 1 0; 0 1; }