Home > Operation and Maintenance > Nginx > How to use nginx rewrite function

How to use nginx rewrite function

WBOY
Release: 2023-05-17 13:49:32
forward
3455 people have browsed it

    Preface

    When you browse some websites, have you noticed that when you enter: www.abc.com or www.abcd.com? At all times, the page can display the homepage content of www.abc.com normally. This is a usage scenario of nginx rewrite.

    Introduction to rewrite

    rewrite is an important basic function provided by the Nginx server. Its main function is to realize URL address rewriting

    rewrite function implementation depends on Due to the support of pcre, so before compiling and installing the Nginx server, you need to install the pcre library (nginx uses the ngx_http_rewrite_module module to parse and process the relevant configuration of the Rewrite function)

    Before truly understanding the use of rewrite, it is necessary to have a comprehensive system Learn the instructions and syntax related to rewrite. Let’s learn about them one by one.

    Rewrite rules and instructions

    set instruction

    This instruction is used to set a new Variables.

    How to use nginx rewrite function

    • variable, variable name, the variable name must use "$" as the first character of the variable, and cannot be used with the Nginx server The default global variable has the same name;

    • value: variable value, which can be a string, other variables or a combination of variables, etc.;

    A simple case

    server {
        listen 8081;
        server_name localhsot;
        location /server {
                set $name zhangsan;
                set $age 19;
                default_type text/plain;
                return 200 $name=$age;
        }
    }
    Copy after login

    Restart the nginx service, and then access the browser to observe the effect

    How to use nginx rewrite function

    The following is a list of commonly used Rewrite Global variables

    These variables can be flexibly selected according to your own business during use

    VariablesDescription
    $argsThe variable stores the request instructions in the request URL. For example, "arg1=value1&arg2=value2" in http://IP:8080?arg1=value1&args2=value2 has the same function as $query_string
    $http_user_agentVariable Stores the proxy information for users to access the service (if accessed through a browser, the relevant version information of the browser is recorded)
    $hostThe variable stores the access The server_name value of the server
    $document_uri variable stores the URI of the current access address. For example, "/server" in http://IP/server?id=10&name=zhangsan has the same function as $uri
    $document_rootThe variable stores The root value of the location corresponding to the current request. If not set, it defaults to the location of Nginx's own html directory.
    $content_lengthThe variable stores the Content in the request header. The value of -Length
    $content_typeThe variable stores the value of Content-Type in the request header
    $ The http_cookie variable stores the cookie information of the client. You can add cookie data through add_header Set-Cookie’cookieName=cookieValue’
    $limit_rateThe variable is stored in the Nginx server's limit on the network connection rate, which is the value set for the limit_rate directive in the Nginx configuration. The default is 0, no limit.
    $remote_addr The variable stores the IP address of the client
    $remote_portThe variable stores the port number for establishing a connection between the client and the server
    $remote_userThe variable stores the username of the client, which requires an authentication module to obtain
    $schemeThe access protocol is stored in the variable
    $server_addrThe address of the server is stored in the variable
    $server_nameThe variable stores the name of the server where the client request arrives
    $server_portThe variable stores the port number of the server where the client request arrives
    $server_protocolThe variable stores the version of the client request protocol, such as "HTTP/1.1"
    $request_body_fileThe variable stores the name of the local file resource sent to the back-end server
    $request_methodThe variable stores the client's request method, such as "GET", "POST", etc.
    $request_filenameThe variable stores the path name of the currently requested resource file
    $request_uriThe variable stores the URI of the current request and carries the request parameters, such as "/server?id=10&name=zhangsan name" in http://IP/server?id=10&name=zhangsan

    我们来随机测试下几个指令的使用吧

    $args

    server {
        listen 8081;
        server_name localhsot;
        location /server {
                set $name zhangsan;
                set $age 19;
                default_type text/plain;
                return 200 $name=$age=$args;
        }
    }
    Copy after login

    How to use nginx rewrite function

    How to use nginx rewrite function

    How to use nginx rewrite function

    其他的指令有兴趣的同学可以自行尝试,下面使用这些指令完成一个需求

    自定义日志输出格式,将请求的日志输出到自定义的日志中

    具体配置如下:

    log_format main '$remote_addr - $request - $status - $request_uri - $http_user_agent';
       server {
            listen 8081;
            server_name localhsot;
            location /server {
                    access_log logs/access-server.log main;
                    set $name zhangsan;
                    set $age 19;
                    default_type text/plain;
                    return 200 $name=$age=$args=$http_user_agent;
            }
        }
    Copy after login

    通过这种方式,就可以实现自定义请求的相关参数输出到自定义的日志文件中

    How to use nginx rewrite function

    if指令

    该指令用来支持条件判断,并根据条件判断结果选择不同的Nginx配置

    How to use nginx rewrite function

    condition为判定条件,可以支持以下写法:

    1)变量名称,如果变量名对应的值为空或者是0,if都判断为false,其他条件为true

    if ($param) { 
    
    }
    Copy after login
    location /testif {
                    set $username 'zhangsan';
                    default_type text/plain;
                    if ($username){
                            return 200 success;
                    }
                    return 200 'params is empty';
    }
    Copy after login

    How to use nginx rewrite function

    2) 使用"=“和”!="比较变量和字符串是否相等,满足为true,不满足为false

    if ($request_method = POST) { 
     return 405; 3
    }
    Copy after login

    注意:此处和Java不一样的是字符串不需加引号

    3)使用正则表达式对变量匹配

    • 匹配成功返回true,否则返回false;

    • 变量与正则表达式之间使用"“,”“,”!“,”!"来连接;

    • “~” 代表匹配正则表达式过程中区分大小写;

    • "~*"代表匹配正则表达式过程中不区分大小写;

    • "!“和”!*"刚好和上面取相反值,如果匹配上返回false,匹配不上返回true;

    if ($http_user_agent ~ MSIE) {
        #$http_user_agent的值中是否包含MSIE字符串,如果包含返回 true 
    }
    Copy after login

    注意:正则表达式字符串一般不需要加引号,但是如果字符串中包含"}“或者是”;"等字符时,就需要把引号加上

    if ($http_user_agent ~ Safari){
                            return 200 Chrome;
      }
    Copy after login

    How to use nginx rewrite function

    4)判断请求文件是否存在使用"-f"和"!-f"

    • 当使用"-f"时,如果请求的文件存在返回true,不存在返回false;

    • 当使用"!f"时,如果请求文件不存在,但该文件所在目录存在返回true,文件和目录都不存在返回false,如果文件存在返回false;

    if (-f $request_filename){
        #判断请求的文件是否存在
    }
    
    if (!-f $request_filename){
        #判断请求的文件是否不存在
    }
    Copy after login

    案例展示

    location /file {
                    root html;
                    default_type text/html;
                    if (!-f $request_filename){
                            return 200 &#39;<h2>not find file</h2>&#39;;
                    }
            }
    Copy after login

    当访问目录下不存在的文件时,将会看到如下的异常返回

    How to use nginx rewrite function

    5) 判断请求的目录是否存在使用"-d"和"!-d"

    • 当使用"-d"时,如果请求的目录存在,if返回true,如果目录不存在则返回false;

    • 当使用"!-d"时,如果请求的目录不存在但该目录的上级目录存在则返回true,该目录和它上级目录都不存在则返回false,如果请求目录存在也返回false;

    使用"-e"和"!-e"来检查所请求的目录或文件是否存在

    • 当使用"-e",如果请求的目录或者文件存在时,if返回true,否则返回false;

    • 当使用"!-e",如果请求的文件和文件所在路径上的目录都不存在返回true,否则返回false;

    7) 判断请求的文件是否可执行使用"-x"和"!-x"

    • 当使用"-x",如果请求的文件可执行,if返回true,否则返回false;

    • 当使用"!-x",如果请求文件不可执行,返回true,否则返回false; break指令

    该指令用于中断当前相同作用域中的其他Nginx配置。在Nginx的配置中,与该指令处于相同作用域的指令中,位于该指令之前的配置生效,位于之后的配置则无效

    How to use nginx rewrite function

    location /{
        if ($param){
    
            set $id $1;
            break;
            limit_rate 10k;
        }
    }
    Copy after login

    案例演示

    location /break {
                    default_type text/plain;
                    set $username MIKE;
                    if ($args){
                            set $username JIM;
                            break;
                            set $username JODAN;
                    }
                    return 200 $username;
            }
    Copy after login

    How to use nginx rewrite function

    return指令

    该指令用于完成对请求的处理,直接向客户端返回响应状态代码。在return后的所有Nginx配置都是无效的

    How to use nginx rewrite function

    • code,为返回给客户端的HTTP状态代理。可以返回的状态代码为0~999的任意HTTP状态代理;

    • text:为返回给客户端的响应体内容,支持变量的使用;

    • URL:为返回给客户端的URL地址;

    location /return {
                    default_type application/json;
                    return 200 &#39;{id:1,name:jike}&#39;;
            }
    Copy after login

    How to use nginx rewrite function

    rewrite指令

    该指令通过正则表达式的使用来改变URI。URL可以同时匹配并处理一个或多个指令,按照顺序进行处理

    URL和URI的区别

    • URI:统一资源标识符

    • URL:统一资源定位符

    How to use nginx rewrite function

    • regex,用来匹配URI的正则表达式;

    • 替换:在匹配成功后,用于替换被截取字符串的URI内容。如果该字符串是以"http://"或者"https://"开头的,则不会继续向下对URI进行其他处理,而是直接返回重写后的URI给客户端;

    • flag:用来设置rewrite对URI的处理行为,可选值有如下

    last break redirect permanent

    last : 终止继续在本location中处理接收到的URI,并将此处重写的URI作为一个新的URI,使用各location块进行处理。该标志将重写的URI重写在server块中执行,为重写后的URI提供了转入到其他location块的机会;

    break : 将此处重写的URI作为一个新的URI,在本块中继续处理,该标志重写后的地址在当前的location块中执行,不会将新的URI转向其他的location块;

    redirect : 将重写后的URI返回给客户端,状态码为302,指明是临时重定向URI,主要用在replacement变量不是以 “http://”或“https://”开头的情况;

    redirect : 将重写后的URI返回给客户端,状态码为302,指明是临时重定向URI,主要用在replacement变量不是以 “http://”或“https://”开头的情况;

    permanent : 将重写后的URI返回给客户端,状态码为301,指明是临时重定向URI,主要用在replacement变量不是以 “http://”或“https://”开头的情况;

    示例1

    location /rewirte {
                    rewrite ^/rewrite/url\w*$ https://www.baidu.com;
                    rewrite ^/rewrite/(test)/\w*$ /$1;
                    rewrite ^/rewrite/(hello)/\w*$ /$1;
            }
            location /test {
                    default_type text/plain;
                    return 200 "hello success";
            }
    Copy after login

    示例2

    location /rewirte {
                    rewrite ^/rewrite/url\w*$ https://www.baidu.com;
                    rewrite ^/rewrite/(test)/\w*$ /$1 last;
                    rewrite ^/rewrite/(hello)/\w*$ /$1 last;
            }
            location /test {
                    default_type text/plain;
                    return 200 "hello success";
            }
    Copy after login

    rewrite_log指令

    该指令配置是否开启URL重写日志的输出功能

    How to use nginx rewrite function

    开启后,URL重写的相关日志将以notice级别输出到error_log指令配置的日志文件汇总

    location /rewirte {
    				rewrite_log on;
    				error_log logs/error.log notice;
                    rewrite ^/rewrite/url\w*$ https://www.baidu.com;
                    rewrite ^/rewrite/(test)/\w*$ /$1 last;
                    rewrite ^/rewrite/(hello)/\w*$ /$1 last;
            }
    Copy after login

    一、rewrite配置域名跳转

    有很多大型网站,在起步的时候,比如域名为 : www.haoyijia.com,但是域名太长所带来的问题就是不方便记忆,于是后面改成 www.hyj.com,问题是,一些老用户之前一直习惯了那个长域名,如何在老用户输入长域名的时候仍然可以跳转到新的短域名上呢?就可以考虑使用rewrite的功能;下面在本地做一下模拟。

    配置步骤:

    1、准备两个域名

    这里我直接在本地模拟2个域名,通过在本地的hosts文件配置下就可以了

    How to use nginx rewrite function

    2、配置nginx.conf文件

    server {
    
    		listen 80;
    		server_name www.zcy.com www.zhangcongyi.com;
    		rewrite ^/ http://www.jd.com permanent;
    	}
    Copy after login

    重启nginx服务,浏览器访问:www.zcy.com 或者www.zhangcongyi.com,观察效果

    How to use nginx rewrite function

    How to use nginx rewrite function

    How to use nginx rewrite function

    How to use nginx rewrite function

    二、rewrite配置独立域名

    一个完整的项目包含多个模块,比如购物网站有商品商品搜索模块、商品详情模块、购物车模块等,那么我们如何为每一个模块设置独立的域名。

    server{
    		listen 80;
    		server_name search.hm.com;
    		rewrite ^(.*) http://www.hm.com/bbs$1 last;
    	}
    	server{
    		listen 81;
    		server_name item.hm.com;
    		rewrite ^(.*) http://www.hm.com/item$1 last;
    	}
    	server{
    		listen 82;
    		server_name cart.hm.com;
    		rewrite ^(.*) http://www.hm.com/cart$1 last;
    	}
    Copy after login

    本地的hosts文件添加如下配置

    How to use nginx rewrite function

    重启nginx服务,可以在浏览器访问下观察效果如何

    How to use nginx rewrite function

    三、rewrite配置目录合并

    搜索引擎优化(SEO)是一种利用搜索引擎的搜索规则,来提供目的网站的有关搜索引擎内排名的方式;

    我们在创建自己的站点时,可以通过很多种方式有效提供搜索引擎优化的程度,其中有一项就包含URL的目录层级一般不要超过三层,否则的话不利于搜索引擎的搜索也给客户端的输入带来了负担;

    但是将所有的文件放在一个目录下又会导致文件资源管理混乱,并且访问文件的速度也会随着文件增多而慢下来,这两个问题是相互矛盾的,使用rewrite就可以解决上述问题;

    举例,网站中有一个资源文件的访问路径时,比如访问:/server/11/22/33/44/20.html,也就是说20.html存在于第5级目录下,如果想要访问该资源文件,客户端的URL地址就要写成http://www.web.name/server/11/22/33/44/20.html;

    server {
    	listen 80;
    	server_name www.web.com;
    	location /server{
    		root html;
    	}
    }
    Copy after login

    How to use nginx rewrite function

    How to use nginx rewrite function

    但是这个是非常不利于SEO搜索引擎优化的,同时客户端也不好记,使用rewrite我们可以进行如下配置:

    server {
    	listen 80;
    	server_name www.web.com;
    	location /server{
    		rewrite ^/server-([0-9]+)-([0-9]+)-([0-9]+)- ([0-9]+)\.html$ /server/$1/$2/$3/$4/$5.html last;
    	}
    }
    Copy after login

    The above is the detailed content of How to use nginx rewrite function. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template