Nginx Rewrite

符号

* ~ 为区分大小写匹配 
* ~* 为不区分大小写匹配 
* !~和!~*分别为区分大小写不匹配及不区分大小写不匹配 

文件及目录匹配

    * -f和!-f用来判断是否存在文件
    * -d和!-d用来判断是否存在目录
    * -e和!-e用来判断是否存在文件或目录
    * -x和!-x用来判断文件是否可执行

flag标记

    * last 相当于Apache里的[L]标记,表示完成rewrite
    * break 终止匹配, 不再匹配后面的规则
    * redirect 返回302临时重定向 地址栏会显示跳转后的地址
    * permanent 返回301永久重定向 地址栏会显示跳转后的地址

全局变量

    $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

一些例子

    用户使用ie的使用重定向到/nginx-ie目录下
    if ($http_user_agent ~ MSIE) {
        rewrite ^(.*)$ /nginx-ie/$1 break;
    }
    
    禁止htaccess
    location ~//.ht {
         deny all;
    }

    禁止多个目录
    location ~ ^/(cron|templates)/ {
         deny all;
        break;
    }
    
    禁止以/data开头的文件
    location ~ ^/data {
         deny all;
    }

    只充许固定ip访问网站,并加上密码
    root  /opt/htdocs/www;
    allow   208.97.167.194;
    allow   222.33.1.2;
    allow   231.152.49.4;
    deny    all;
    auth_basic "C1G_ADMIN";
    auth_basic_user_file htpasswd;
    
    文件和目录不存在的时候重定向
    if (!-e $request_filename) {
        proxy_pass http://127.0.0.1;
    }
原文地址:https://www.cnblogs.com/dreamans/p/2784235.html