Nginx rewrite
rewrite规则作用
rewirte规则也叫规则重写,主要实现浏览器访问URL实现跳转的功能。
支持正则表达式。
主要用途:
- SEO优化,方便爬虫爬取网站页面。
- 隐藏网站真实地址,安全并且使浏览器显示更加美观。
- URL重定向访问跳转。
rewrite
语法
rewrite regex replacement [flag]
last: 本条规则匹配完成后继续向下匹配新的location URI规则
break: 本条规则匹配完成后终止,不再匹配后续任何规则
redirect: 返回302临时重定向
permanent: 返回301永久重定向
案例
rewrite ^/(.*) http://www.tz.com/$1 permanent;
说明:
rewrite为固定关键字,表示开始进行rewrite匹配规则
regex部分是 ^/(.*) ,这是一个正则表达式,匹配完整的域名和后面的路径地址
replacement部分是http://www.tz.com/$1,$1是取自regex部分()里的内容。匹配成功后跳转到的URL。
flag部分的permanent表示永久301重定向标记,即跳转到新的 http://www.tz.com/$1 地址上
regex: Nginx规则表达式,常用如下
[word]: 匹配字符串word
[^word]: 不匹配字符串word
tz|tz666: 可选择的字符串tz|tz666
?: 匹配前面的字符出现0~1次
*: 匹配前面的字符出现0到多次
+: 匹配前面的字符出现1到多次
^: 字符串开始标志
$: 字符串结尾标志
\n: 转义符标志
.: 匹配除“\n”之外的所有单个字符
Nginx rewrite变量
用于匹配HTTP请求头信息、浏览器主机名、URL等,详解如下

案例
301永久重定向跳转
$ cat /usr/local/nginx/conf/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#增加一个server区块用作跳转
server {
listen 80
server_name www.tz.com
rewrite ^/(.*) http://www.tz.com/index01.html permanent;
}
server {
listen 80;
server_name localhost;
default_type text/html;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
这样访问www.tz.com就会跳转到www.tz.com/index01.html页面上。
其他案例
if条件判断可以存在server跟location块中
#访问tz.com跳转到www.baidu.com
if ( $host = 'tz.com'){
rewrite ^/(.*)$ http://www.baidu.com/$1 redirect;
}
访问/tz/test01/ 跳转到/newindex.html
rewrite ^/tz/test01/$ /newindex.html last;
不管访问什么都跳转到www.tz.com
if ( $host != 'www.tz.com' ){
rewrite ^/(.*)$ http://www.tz.com/$1 permanent;
}
访问文件和目录不存在时跳转到index.php
if ( ! -e $request_filename ){
rewrite ^/(.*)$ /index.php last;
}
判断浏览器user agent跳转
#如果是谷歌浏览器访问/index.html就跳转到www.tz.com
if ( $http_user_agent ~* Chrome) {
rewrite ^/index.html http://www.tz.com/ redirect;
}
#如果是IE浏览器访问index.html或者是其他后缀,就跳转到/ie/index.html或其他后缀上去
if ( $http_user_agent ~ MSIE) {
rewrite ^(.*)$ /ie/$1 redirect;
}
禁止访问以.sh .flv .mp3后缀的文件
location ~ .* \.(sh|flv|mp3)$
{
retrun 403;
}
将使用移动客户端访问的用户跳转到m.tz.com
if ( $http_user_agent ~* "(Android)|(iPhone)|(Mobile)|(WAP)|(UCWEB)")
{
rewrite ^/$ http://m.tz.com/ permanent;
}
匹配URL访问参数跳转
if ( $args ~* tid=13)
{
return 404;
}
访问/10690/tz/123跳转到/index.php?tid/10690/items=123上去
$1表示[0-9]匹配到的内容即10690,$2表示(.+)匹配到的内容即123
[0-9]表示任意一个数字,+表示前面的字符出现多次,(.+)表示任意多个字符
rewrite ^/([0-9]+)/tz/(.+)$ /index.php?tid/$1/items=$2 last;
后记
曝光Linux企业运维实战书中内容比较详尽,贴近生产环境案例,但部分代码有小错误需要注意。
学习来自:Crazymagic博客,Brian Zhu博客,去玩儿博客,曝光Linux企业运维实战 第十四章

浙公网安备 33010602011771号