ngx_http_rewrite_module模块允许正则替换URI,返回页面重定向,和按条件选择配置。
rewrite的主要功能是实现URL地址的重定向。如伪静态、网址换新域名后,让旧的访问跳转到新的域名上、隐藏index.php等。
隐藏index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
if (!-e $request_filename){
rewrite ^/(.*) /index.php last;
}
index index.html index.htm index.php;
#autoindex on;
}
break和last
break:只匹配一次,停止匹配。
last:如果指令改变了URI,按新的URI查找location。这个循环至多重复10次,之后nginx返回错误500 (Internal Server Error)。
如
location /api {
rewrite ^/api/(.*)$ /test/$1 last;
}
location /test {
rewrite ^/test/(.*)$ /api/public/index.html/$1 break;
}
当/api/aa 进入location /api时,被修改URI,然后按照新的URI继续查找location去匹配,匹配到location /test中。
伪静态
location /ecshop {
root /www;
# /ecshop/goods-3.html ---->/ecshop/goods.php?id=3
rewrite goods-(\d+)\.html$ /ecshop/goods.php?id=$1 break;
}