683 views
Linux-基础命令

Nginx-rewrite

Rewrite规则的最后一项参数为flag标记,支持的flag标记主要有以下:

last :相当于Apache里的(L)标记,表示完成rewrite;

break;本条规则匹配完成后,终止匹配,不再匹配后面的规则;

redirect:返回302临时重定向,浏览器地址会显示跳转后的URL地址,Nginx返回response状态码 302。

permanent:返回301永久重定向,浏览器地址栏会显示跳转后的新的URL地址。 Nginx返回response状态码 301。

last和break用来实现URL重写,浏览器地址栏URL地址不变。

[code]

实例:

1、rewrite / /index.html last; 访问/时,会直接重写到/index.html 但是会隐藏index.html后缀

2、rewrite / http://192.168.77.71 permanent; 访问/时,会重定向到192.168.77.71

3、rewrite / http://192.168.77.71/index.html last;

4、rewrite ^/(.*)$ www.baidu.com/$1 permanent; 访问的地址/(后缀)直接重定向到www.baidu.com/(后缀)

5、if ($HOST != www.ying.com) { rewrite ^/(.*)$ www.baidu.com permanent; } 如果 域名不是www.ying.com,则跳转到www.baidu.com去

6、rewrite ^/index.html http://www.baidu.com permanent; 匹配访问的是index.html的就跳转到百度去

rewrite ^/index01.html http://192.168.77.71 permanent; 匹配访问的是index01.html的就跳转到192.168.77.1去

7、rewrite ^/(.*\.html)$ www.baidu.com permanent;匹配任何以html结尾的信息,都跳转到百度去

8、if ($request_uri ~! ‘index.html’) {rewrite ^/(.*)$ /index.html permanent;} 将不是index.html的uri转为index.html的

9、if ($http_user_agent ~* (Wget|wget|curl) ) {return 500;} 将匹配到Wget|wget|curl,都返回500

10、if ($request_uri ~ ‘/upload/index.html’) {rewrite /(.*/.*\.html)$ /hehe.html last;} 将匹配到uri为/upload/index.html的,跳转到/hehe.html

11、if ($host = ‘www.ying.com’){rewrite / http://blog.xiaoqying.com/ last;} 将www.ying.com跳转到blog.xiaoqying.com

12、if( !-e $request_filename ){rewrite ^/(.*)$ index.php last;} 当访问的文件和目录不存在时,重定向到某个php文件

13、location ~ ^/(cron|templates)/ {deny all;break;} 禁止访问多个目录

14、rewrite^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/$3.html last;

将多级目录下的文件转成一个文件,增强seo效果/job-123-456-789.html 指向/job/123/456/789.html

15、location ~ .*\.(sh|flv|mp3)$ {return 403;} 禁止访问以.sh,.flv,.mp3为文件后缀名的文件

16、rewrite ^/(\d+)/(.+)/ /$2?id=$1 last; 目录对换 /123456/xxxx ====> /xxxx?id=123456

17、if( $http_user_agent ~ MSIE) {rewrite ^(.*)$ /ie/$1 break;} 如果客户端使用的是IE浏览器,则重定向到/ie目录下

18、if (!-e $request_filename) {proxy_pass http://127.0.0.1;} 文件和目录不存在的时候重定向到127.0.0.1

19、rewrite ^/b/?$ /bbs permanent; 将访问/b跳转到/bbs目录上去

20、根据Referer信息防止盗链

location ~*\.(gif|jpg|png|swf|flv)$ {

valid_referers none blocked *.ying.com;

if ($invalid_referer) {

rewrite ^/(.*) http://www.ying.com/error.html

} }

[/code]

Leave a Reply

影子专属博客 赣ICP备17013143号