Use lua to configure the anti hotlinking function of the Nginx server

  • 2020-05-10 23:26:22
  • OfStack

The download server is often hotlinking, which leads to the waste of a lot of resources of the server. Because the server USES nginx as web server. There are many anti-hotlinking methods for nginx. You can use the ready-made anti-hotlinking module nginx-accesskey-2.0.3, which can be added when compiling ningx.
Because of other business needs, nginx has compiled the lua module, so we want to use lua to realize the anti-hotlinking function of the download server (lua_nginx_module, Nginx module of lua, lua_nginx_module, and we won't discuss the configuration process in detail here), so we can get rid of the accesskey module. The idea is to generate a processed download link, and the download server processes the download link. If it succeeds, it downloads, and if it fails, it blocks it. Here is a detailed configuration example:
1. Generate the nginx configuration of the link on the download page
Configuration of download.ofstack.com:


server  
{  
    listen    80;  
    server_name download.ofstack.com;  
    index index.htm index.html;  
    root /data/www/download;  
    ssi on;  
 
    location /  
    {  
        set_by_lua $downkey '  
            return ngx.md5("encryption" .. ngx.var.remote_addr .. "suffix")  
        ';  
    }  
} 

Note: ssi must be turned on to get the nginx custom variable downkey from the html page. In this way, the processed url can be generated. The strings encryption and suffix are customized and can be changed to any other character.
Test index.html code:
2. Download server nginx configuration:


server  
{  
    listen    80;  
    server_name down.ofstack.com;  
    index index.htm index.html;  
    root /data/www/down;  
    limit_conn  one 1;  
    set $limit_rate 1000k;  
 
  location /  
    {  
        set_by_lua $foo '  
            if string.sub(ngx.var.uri, 2, 33) == ngx.md5("encryption" .. ngx.var.remote_addr .. "suffix") then  
                return 1 
            else 
                return 0 
            end  
        ';  
 
        if ($foo = 1)  
        {  
            rewrite "^/([0-9a-z]{32})(.*?)$"    $2 break;  
        }  
        if ($foo = 0)  
        {  
            rewrite ^/ http://download.ofstack.com/404.htm redirect;  
        }  
    }  
} 

When you copy the link to another machine, the error page opens.



Related articles: