last-完成rewrite指令的处理,之后搜索对应的URI和location;break-完成rewrite指令的外理
[root@web01 app]# cat /app/server/nginx/conf/vhosts/default.confserver { listen 80 default_server; server_name localhost; root /app/www; location / { root /app/www/html; index index.html index.htm; rewrite "/x/t.html" /y/t.html break; } location /y/ { root /app/www/html/other; }}
[root@web01 other]# tree /app/www/html/ /app/www/html/ ├── index.html ├── other │ └── y │ └── t.html └── y └── t.html 3 directories, 3 files [root@web01 other]# cat /app/www/html/y/t.html yyy [root@web01 other]# cat /app/www/html/other/y/t.html other----->last [root@web01 other]#
[root@web01 app]# curl http://192.168.1.24/x/t.htmlyyy
当请求/x/t.html,符合rewrite规则,所以进行调整,调整的地址为/y/t.html,由于使用的flag是break,所以在 “location /”中进行跳转,结果是/app/www/html/y/t.html。但如果flag为last,那么/y/t.html将在"server"标签中重新执 行,由于存在一个“location /y/”,所以跳转被重新指定到“location /y/”标签,所以这个时候的结果为/app/www/html/other/y/t.html
如下测式:
[root@web01 other]# cat /app/www/html/other/y/t.html other----->last[root@web01 other]# cat /app/server/nginx/conf/vhosts/default.confserver { listen 80 default_server; server_name localhost; root /app/www; location / { root /app/www/html; index index.html index.htm; #rewrite "/x/t.html" /y/t.html break; rewrite "/x/t.html" /y/t.html last;#注意这里已经改成last } location /y/ { root /app/www/html/other; }}[root@web01 other]# curl http://192.168.1.24/x/t.htmlother----->last
注意:使用last,如果配置不当,可能引起死循环。
[root@web01 www]# cat /app/server/nginx/conf/vhosts/default.confserver { listen 80 default_server; server_name localhost; root /app/www; location / { rewrite /last/ /q.html last;#是相对于root /app/www 所以真实的访问路径是 /app/www/q.html rewrite /break/ /q.html break; } location =/q.html { return 400; } location ~ .*\.(php|php5)?$ { #fastcgi_pass unix:/tmp/php-cgi.sock; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi.conf; } access_log /app/log/nginx/access/default.log;}[root@web01 www]# tree /app/www//app/www/├── index.php└── q.html0 directories, 2 files[root@web01 www]# cat /app/www/q.html clnking@163.com[root@web01 www]# curl 192.168.1.24/last/q.html400 Bad Request 400 Bad Request
nginx/1.4.4 [root@web01 www]# curl 192.168.1.24/break/q.htmlclnking@163.com
- last一般写在server和if中,而break一般使用在location中
- last不终止重写后的url匹配,即新的url会再从server走一遍匹配流程,而break终止重写后的匹配
- break和last都能组织继续执行后面的rewrite指令
在location
里一旦返回break
则直接生效并停止后续的匹配location
server { location / { rewrite /last/ /q.html last; rewrite /break/ /q.html break; } location = /q.html { return 400; }}
- 访问
/last/
时重写到/q.html
,然后使用新的uri
再匹配,正好匹配到locatoin = /q.html
然后返回了400
- 访问
/break
时重写到/q.html
,由于返回了break
,则直接停止了.