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.
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; } }
Restart the nginx service, and then access the browser to observe the effect
The following is a list of commonly used Rewrite Global variables
These variables can be flexibly selected according to your own business during use
Variables | Description |
---|---|
$args | The 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_agent | Variable Stores the proxy information for users to access the service (if accessed through a browser, the relevant version information of the browser is recorded) |
$host | The 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_root | The 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_length | The variable stores the Content in the request header. The value of -Length |
$content_type | The 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_rate | The 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_port | The variable stores the port number for establishing a connection between the client and the server |
$remote_user | The variable stores the username of the client, which requires an authentication module to obtain |
$scheme | The access protocol is stored in the variable |
$server_addr | The address of the server is stored in the variable |
$server_name | The variable stores the name of the server where the client request arrives |
$server_port | The variable stores the port number of the server where the client request arrives |
$server_protocol | The variable stores the version of the client request protocol, such as "HTTP/1.1" |
$request_body_file | The variable stores the name of the local file resource sent to the back-end server |
$request_method | The variable stores the client's request method, such as "GET", "POST", etc. |
$request_filename | The variable stores the path name of the currently requested resource file |
$request_uri | The 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; } }
其他的指令有兴趣的同学可以自行尝试,下面使用这些指令完成一个需求
自定义日志输出格式,将请求的日志输出到自定义的日志中
具体配置如下:
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; } }
通过这种方式,就可以实现自定义请求的相关参数输出到自定义的日志文件中
if指令
该指令用来支持条件判断,并根据条件判断结果选择不同的Nginx配置
condition为判定条件,可以支持以下写法:
1)变量名称,如果变量名对应的值为空或者是0,if都判断为false,其他条件为true
if ($param) { }
location /testif { set $username 'zhangsan'; default_type text/plain; if ($username){ return 200 success; } return 200 'params is empty'; }
2) 使用"=“和”!="比较变量和字符串是否相等,满足为true,不满足为false
if ($request_method = POST) { return 405; 3 }
注意:此处和Java不一样的是字符串不需加引号
3)使用正则表达式对变量匹配
匹配成功返回true,否则返回false;
变量与正则表达式之间使用"“,”“,”!“,”!"来连接;
“~” 代表匹配正则表达式过程中区分大小写;
"~*"代表匹配正则表达式过程中不区分大小写;
"!“和”!*"刚好和上面取相反值,如果匹配上返回false,匹配不上返回true;
if ($http_user_agent ~ MSIE) { #$http_user_agent的值中是否包含MSIE字符串,如果包含返回 true }
注意:正则表达式字符串一般不需要加引号,但是如果字符串中包含"}“或者是”;"等字符时,就需要把引号加上
if ($http_user_agent ~ Safari){ return 200 Chrome; }
4)判断请求文件是否存在使用"-f"和"!-f"
当使用"-f"时,如果请求的文件存在返回true,不存在返回false;
当使用"!f"时,如果请求文件不存在,但该文件所在目录存在返回true,文件和目录都不存在返回false,如果文件存在返回false;
if (-f $request_filename){ #判断请求的文件是否存在 } if (!-f $request_filename){ #判断请求的文件是否不存在 }
案例展示
location /file { root html; default_type text/html; if (!-f $request_filename){ return 200 '<h2 id="not-nbsp-find-nbsp-file">not find file</h2>'; } }
当访问目录下不存在的文件时,将会看到如下的异常返回
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的配置中,与该指令处于相同作用域的指令中,位于该指令之前的配置生效,位于之后的配置则无效
location /{ if ($param){ set $id $1; break; limit_rate 10k; } }
案例演示
location /break { default_type text/plain; set $username MIKE; if ($args){ set $username JIM; break; set $username JODAN; } return 200 $username; }
return指令
该指令用于完成对请求的处理,直接向客户端返回响应状态代码。在return后的所有Nginx配置都是无效的
code,为返回给客户端的HTTP状态代理。可以返回的状态代码为0~999的任意HTTP状态代理;
text:为返回给客户端的响应体内容,支持变量的使用;
URL:为返回给客户端的URL地址;
location /return { default_type application/json; return 200 '{id:1,name:jike}'; }
rewrite指令
该指令通过正则表达式的使用来改变URI。URL可以同时匹配并处理一个或多个指令,按照顺序进行处理
URL和URI的区别
URI:统一资源标识符
URL:统一资源定位符
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"; }
示例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"; }
rewrite_log指令
该指令配置是否开启URL重写日志的输出功能
开启后,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; }
一、rewrite配置域名跳转
有很多大型网站,在起步的时候,比如域名为 : www.haoyijia.com,但是域名太长所带来的问题就是不方便记忆,于是后面改成 www.hyj.com,问题是,一些老用户之前一直习惯了那个长域名,如何在老用户输入长域名的时候仍然可以跳转到新的短域名上呢?就可以考虑使用rewrite的功能;下面在本地做一下模拟。
配置步骤:
1、准备两个域名
这里我直接在本地模拟2个域名,通过在本地的hosts文件配置下就可以了
2、配置nginx.conf文件
server { listen 80; server_name www.zcy.com www.zhangcongyi.com; rewrite ^/ http://www.jd.com permanent; }
重启nginx服务,浏览器访问:www.zcy.com 或者www.zhangcongyi.com,观察效果
二、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; }
本地的hosts文件添加如下配置
重启nginx服务,可以在浏览器访问下观察效果如何
三、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; } }
但是这个是非常不利于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; } }
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!

本篇文章给大家带来了关于nginx的相关知识,其中主要介绍了nginx拦截爬虫相关的,感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。

高并发系统有三把利器:缓存、降级和限流;限流的目的是通过对并发访问/请求进行限速来保护系统,一旦达到限制速率则可以拒绝服务(定向到错误页)、排队等待(秒杀)、降级(返回兜底数据或默认数据);高并发系统常见的限流有:限制总并发数(数据库连接池)、限制瞬时并发数(如nginx的limit_conn模块,用来限制瞬时并发连接数)、限制时间窗口内的平均速率(nginx的limit_req模块,用来限制每秒的平均速率);另外还可以根据网络连接数、网络流量、cpu或内存负载等来限流。1.限流算法最简单粗暴的

实验环境前端nginx:ip192.168.6.242,对后端的wordpress网站做反向代理实现复杂均衡后端nginx:ip192.168.6.36,192.168.6.205都部署wordpress,并使用相同的数据库1、在后端的两个wordpress上配置rsync+inotify,两服务器都开启rsync服务,并且通过inotify分别向对方同步数据下面配置192.168.6.205这台服务器vim/etc/rsyncd.confuid=nginxgid=nginxport=873ho

nginx php403错误的解决办法:1、修改文件权限或开启selinux;2、修改php-fpm.conf,加入需要的文件扩展名;3、修改php.ini内容为“cgi.fix_pathinfo = 0”;4、重启php-fpm即可。

跨域是开发中经常会遇到的一个场景,也是面试中经常会讨论的一个问题。掌握常见的跨域解决方案及其背后的原理,不仅可以提高我们的开发效率,还能在面试中表现的更加

nginx禁止访问php的方法:1、配置nginx,禁止解析指定目录下的指定程序;2、将“location ~^/images/.*\.(php|php5|sh|pl|py)${deny all...}”语句放置在server标签内即可。

nginx部署react刷新404的解决办法:1、修改Nginx配置为“server {listen 80;server_name https://www.xxx.com;location / {root xxx;index index.html index.htm;...}”;2、刷新路由,按当前路径去nginx加载页面即可。

linux版本:64位centos6.4nginx版本:nginx1.8.0php版本:php5.5.28&php5.4.44注意假如php5.5是主版本已经安装在/usr/local/php目录下,那么再安装其他版本的php再指定不同安装目录即可。安装php#wgethttp://cn2.php.net/get/php-5.4.44.tar.gz/from/this/mirror#tarzxvfphp-5.4.44.tar.gz#cdphp-5.4.44#./configure--pr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
