1、概念
Nginx的rewrite功能需要pcre软件的支持,即通过perl兼容正则表达式语句进行规则匹配的。 默认参数编译nginx就会支持rewrite的模块,但是也必须要pcre的支持。
rewrite是实现URL重写的关键指令,根据regex(正则表达式)部分内容,重定向到replacement,结尾是flag标记。
2、语法
rewrite <regex> <replacement> [flag];
正则 替代内容 flag标记
正则:perl兼容正则表达式语句进行规则匹配
替代内容:将正则匹配的内容替换成replacement
flag标记:rewrite支持的flag标记
# flag标记说明:
last #本条规则匹配完成终止当前location的规则,继续向下匹配新的location URI规则
break #本条规则匹配完成即终止,不再匹配后面的任何规则
redirect #返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址
3、实例
3.1 域名跳转
方案一:
server {
listen 80;
server_name cluo.com;
rewrite ^/(.*)$ http://www.cluo.com/$1 permanent;
}
server {
listen 80;
server_name www.cluo.com;
location / {
root /data/www/;
index index.html index.htm;
}
}
方案二:
server {
listen 80;
server_name www.cluo.com cluo.com;
if ( $host != 'www.cluo.com' ) {
rewrite ^/(.*)$ http://www.cluo.com/$1 permanent;
}
location / {
root /data/www/;
index index.html index.htm;
}
}
#本地hosts解析配置:
10.0.0.130 www.cluo.com cluo.com
3.2 根据浏览器语言跳转
# 根据浏览器的语言跳转到指定url:
server {
listen 80;
server_name cluo.com www.cluo.com;
root /usr/share/nginx/html/test;
index index.html;
if ( $http_accept_language ~ "zh" ) {
rewrite ^/$ /zh;
}
if ( $http_accept_language ~ "en" ) {
rewrite ^/$ /en;
}
location / {
}
}
mkdir -p /usr/share/nginx/html/test/zh
mkdir -p /usr/share/nginx/html/test/en
echo "this is 中文 " > /usr/share/nginx/html/test/zh/index.html
echo "this is English " > /usr/share/nginx/html/test/en/index.html
3.3 根据终端类型跳转
server {
listen 80;
server_name cluo.com www.cluo.com;
root /usr/share/nginx/html/test;
if ( $http_user_agent ~* "iphone|android" ) {
rewrite ^/(.*)$ http://m.cluo.com/$1;
}
index index.html;
}
server {
listen 80;
server_name m.cluo.com;
root /data/www/m;
index index.html;
location / {
default_type text/html;
return 200 "this is iphone|android html";
}
}
3.4 实现错误页面返回首页
error_page 404 =200 /index.html;