nginx_if

if 空格 (条件) {设定条件进行重写}

条件语法

“=” 判断相等,用于字符比较。

“~”用正则来匹配 (表示区分大小写),“~*” 不区分大小写

“-f -d -e”来判断是否为文件、目录、是否存在

关于if (条件)中的条件,具体还有那些功能大家可以参见官方文档。

以下是这段文字是Module ngx_http_rewrite_module 中的内容。

A condition may be any of the following:

a variable name; false if the value of a variable is an empty string or “0”; 
Before version 1.0.1, any string starting with “0” was considered a false value. 
comparison of a variable with a string using the “=” and “!=” operators; 
matching of a variable against a regular expression using the “~” (for case-sensitive matching) and “~*” (for case-insensitive matching) operators. Regular expressions can contain captures that are made available for later reuse in the 1..1..9 variables. Negative operators “!~” and “!~*” are also available. If a regular expression includes the “}” or “;” characters, the whole expressions should be enclosed in single or double quotes. 
checking of a file existence with the “-f” and “!-f” operators; 
checking of a directory existence with the “-d” and “!-d” operators; 
checking of a file, directory, or symbolic link existence with the “-e” and “!-e” operators; 
checking for an executable file with the “-x” and “!-x” operators.

使用if实现根据浏览器分离访问

//配置文件

location / {
    root   html;
    index  index.html index.htm;
    if ($http_user_agent ~* "MSIE")      #MSIE IE浏览器
      {
        root /var/www/MSIE;
      }
    if ($http_user_agent ~* "Firefox")    #Firefox火狐浏览器
      {
        root /var/www/Firefox;
      }
        }
//添加主页文件
echo "IE" > /var/www/MSIE/test.html
echo "Firefox" > /var/www/Firefox/test.html
  • 测试、分别使用Firefox和IE浏览器访问

网页访问(物理机没有做hosts解析使用LB的IP访问)

原文地址:https://www.cnblogs.com/cljhfy/p/11006055.html