@openxy
2016-03-21T13:03:31.000000Z
字数 2766
阅读 1957
定义规则,改变客户端请求的URI,但仅能改变URI中的的path部分
- https://segmentfault.com/a/1190000002797606
server {listen 80;server_name start.igrow.cn;index index.html index.php;root html;if ($http_host !~ “^star\.igrow\.cn$" {rewrite ^(.*) http://star.igrow.cn$1 redirect;}}
语法: rewrite regex replacement [flag]
作用域: server, location, if
此指令根据表达式来来更改URI,或修改字符串。
指令根据配置文件中的顺序来执行。
pcre 正则表达式,代表被匹配的URI
被重写后的URI,如果需要保留query string,注意附加?
last – 基本上都用这个Flag。
break – 中止Rewirte,不在继续匹配
redirect – 返回临时重定向的HTTP状态302
permanent – 返回永久重定向的HTTP状态301
表达式中可使用的判断式:
-f和!-f用来判断是否存在文件
-d和!-d用来判断是否存在目录
-e和!-e用来判断是否存在文件或目录
-x和!-x用来判断文件是否可执行
可以用作判断的全局变量
例:http://localhost:88/test1/test2/test.php
$host:localhost$server_port:88$request_uri:http://localhost:88/test1/test2/test.php$document_uri:/test1/test2/test.php$document_root:D:\nginx/html$request_filename:D:\nginx/html/test1/test2/test.php
server{listen 80;server_name www.jbxue.com;index index.html index.htm ;root /www;rewrite ^/ http://jbxue.com/;}# 多域名转向server{server_name www.demo.com ;index index.html index.htm;root /www;if ($host ~ "shop\.com") {rewrite ^(.*) http://www.demo.com$1/ permanent;}#三级域名转向if ($http_host ~* "^(.*)\.seller\.taobao\.com$") {rewrite ^(.*) http://taobao.com/$1/;break;}# 目录到子域名{server_name bbs.demo.com news.demo.com;location = / {if ($http_host ~ news\.demo.com$) {rewrite ^.+ http://news.demo.com/forum-831-1.html last;break;}}}
# 将根目录下某个文件夹指向2级目录如/hzbbs/ 指向 /bbs/hz/如果你将last改成permanent,那么浏览器地址栏显示/bbs/hz/rewrite ^/([0-9a-z]+)bbs/(.*)$ /$1/$2 last;# 文件和目录不存在的时候重定向if (!-e $request_filename) {# do something below or otherproxy_pass http://127.0.0.1;}
# 目录自动加“/”,如bbs => bbs/if (-d $request_filename){rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;}# 目录转参数# /123456/xxxx -> /xxxx?id=123456rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;}# abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2if ($host ~* (.*)\.domain\.com) {set $sub_name $1;rewrite ^/sort\/(\d+)\/?$ /index.php?act=sort&cid=$sub_name&id=$1 last;# /job-123-456-789.html 指向/job/123/456/789.htmlrewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
if (!-d $request_filename) {rewrite ^/([a-z-A-Z]+)/([a-z-A-Z]+)/?(.*)$ /index.php?namespace=user&controller=$1&action=$2&$3 last;rewrite ^/([a-z-A-Z]+)/?$ /index.php?namespace=user&controller=$1 last;break;}
# 用户使用ie的使用重定向到/nginx-ie目录if ($http_user_agent ~ MSIE) {rewrite ^(.*)$ /nginx-ie/$1 break;}
location ~* \.(gif|jpg|swf)$ {valid_referers none blocked start.igrow.cn sta.igrow.cn;if ($invalid_referer) {rewrite ^/ http://$host/logo.png;}}