Nginx网站架构实战——08、nginx Rewrite语法详解

Nginx (4.1万) 2018-05-24 10:22:12

前言:

Nginx网站架构实战——01、Nginx介绍及编译安装:传送门

Nginx网站架构实战——02、Nginx信号量:传送门

Nginx网站架构实战——03、nginx虚拟主机配置:传送门

Nginx网站架构实战——04、nginx日志管理:传送门

Nginx网站架构实战——05、nginx定时任务完成日志切割:传送门

Nginx网站架构实战——06、Location详解之精准匹配:传送门

Nginx网站架构实战——07、Location之正则匹配:传送门

常用的命令

    if (条件) {} 设定条件,再进行重写
    set #设置变量
    return  #返回状态码
    break   #跳出rewrite
    rewrite #重写

 

if语法格式

    if 空格 (条件){
        重写模式
    }

    条件又怎么写?
    1. “=”来判断相等, 用于字符串比较
    2. “~” 用正则来匹配(此处的正则区分大小写)
    ~* 不区分大小写的正则
    3. -f -d -e来判断是否为文件,为目录,是否存在.

    [root@tiejiang ~]# cd /usr/local/nginx/
    [root@tiejiang nginx]# vim html/test-if.html
        <html>
            test if and reutrn;
        </html>

    [root@tiejiang nginx]# tail -n 1 logs/access.log 
        192.168.0.102 - - [15/May/2018:03:53:36 +0800] "GET /test-if.html HTTP/1.1" 200 35 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"

Nginx网站架构实战——08、nginx Rewrite语法详解_https://www.tiejiang.org_Nginx_第1张

拒绝一个指定IP访问这个test-if.html页面

    [root@tiejiang ~]# cd /usr/local/nginx/
    [root@tiejiang nginx]# vim conf/nginx.conf
            location / {
                if ($remote_addr = 192.168.0.102) {
                return 403;
            }
                root   html;
                index  index.html index.htm;
            }
    [root@tiejiang nginx]# ./sbin/nginx -s reload

Nginx网站架构实战——08、nginx Rewrite语法详解_https://www.tiejiang.org_Nginx_第2张

拒绝IE浏览器打开任何页面(msie是ie的标识)

    [root@tiejiang ~]# cd /usr/local/nginx/
    [root@tiejiang nginx]# vim conf/nginx.conf
            location / {
                if ($http_user_agent ~ MSIE) {
                rewrite ^.*$ /ie.html;
                break;
            }
                root   html;
                index  index.html index.htm;
            }
    [root@tiejiang nginx]# vim html/ie.html
        <html>
            amn ie, fuck.
        </html>

Nginx网站架构实战——08、nginx Rewrite语法详解_https://www.tiejiang.org_Nginx_第1张
Nginx网站架构实战——08、nginx Rewrite语法详解_https://www.tiejiang.org_Nginx_第4张

用rewrite设置404页面

[root@tiejiang ~]# cd /usr/local/nginx/
[root@tiejiang nginx]# vim html/404.html
    <html>
        this is 404
    </html>
[root@tiejiang nginx]# vim conf/nginx.conf
        location / {
            if ($http_user_agent ~ MSIE) {
            rewrite ^.*$ /ie.html;
            break;
        }
            if (!-e $document_root$fastcgi_script_name){
            rewrite ^.*$ /404.html;
            break;
        }
            root   html;
            index  index.html index.htm;
        }
[root@tiejiang nginx]# ./sbin/nginx -s reload

首先打开一个存在的页面

Nginx网站架构实战——08、nginx Rewrite语法详解_https://www.tiejiang.org_Nginx_第5张

然后再打开一个不存在的页面,现在展示出来我们指定的404页面。

Nginx网站架构实战——08、nginx Rewrite语法详解_https://www.tiejiang.org_Nginx_第6张

THE END

Leave a Reply