在Nginx上编程

Nginx是一款高效的http server,它的第三方扩展性也是非常非常之多。这次有个需求,需要通过链接转换成真正的图片地址,将资源rewrite出去。如果资源不存在将随机一张图片返回。

在开始写的过程中,本来想考虑使用LUA模块,但是这么简单的一个功能,觉得利用rewrite功能就可以了,但是他需要随机,nginx自身是不提供随机数的,所以在官方第三方中找到了一个HttpSetMiscModule模块。

原来是通过rewrite功能,将链接根据需求分割获得相应的参数,然后使用set命令,设定nginx下的环境变量。具体看下面的例子。

    location ^~ /live/screenshots/ {
        valid_referers none blocked *.xx.cn; #设定有效来源
        if ($invalid_referer) {
            return 403;
        }
        expires 1m;
        if ($uri ~ /live/screenshots/(\d+)/(\d+)\.(icon|html|htm|jpeg|jpg|gif|bmp|png|flv|swf|zip|rar|doc|docx|xls|xlsx)) { #针对链接进行分析,取出需要的参数
            set $img_path $document_root/live/screenshots/$1/1.$3; #设定nginx环境变量
            set $roomid $1;
            set $gameid $2;
            set $img_type $3;
        }
        if (-e $img_path) { #判断此文件是否存在
            rewrite ^ /live/screenshots/$roomid/1.$img_type break; #存在就重写链接 
        }
        set_random $rand 1 10; #生成随机数
        set $rand_img /live/capture/$gameid/$rand.jpg;
        set $rand_img_path $document_root$rand_img;
        if (-e $rand_img_path) { #判断随机图片
            rewrite ^ $rand_img break;
        }
        error_page 404 =200 http://img.xx.cn/live/NonePic/none.jpg; #如果没有图片,返回404图片,状态仍然保持200
    }

通过上面的例子和注释,应该大致了解了吧。通过rewrite的if提供的regex以-e -f -d函数功能实现了强大的功能。在利用set功能,将nginx的环境进行配置。这个与写一个php或者其他脚本来比较,速度非常快。

Leave a Comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: