Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

1. 前言

最近打算在blog里面,增加个性化推荐,以增加访问量。这一切的前提是,我要能够标识出每个用户,以及记录用户的浏览记录。这里笔者采用openresty在cookie中写入用户标识,然后在日志中记录下用户的浏览记录,供后续分析使用

2. 详解

1)nginx 配置

    upstream blog {
       server 127.0.0.1:8080;
    }
    server {
        listen       80;        #端口
        server_name  blog.vearne.cc;

        location ^~ /archives/ {
            rewrite_by_lua_file 'conf/lua/set-ck.lua';
            proxy_pass http://blog;
        }

        location /{
            proxy_pass http://blog;
        }
    }

2)Lua脚本 set-ck.lua

如果用户没有对应的cookie “UT_ID”, 则注入cookie的同时,返回一个302临时跳转,
客户再次访问时,由于已经拥有响应cookie,所以可以直接访问后端服务

local cookie_name = "cookie_UT_ID"
local request_uri = ngx.var.request_uri
if ngx.var[cookie_name] == nil then
    local uuid = io.open("/proc/sys/kernel/random/uuid", "r"):read()
    local mycookie = string.format("UT_ID=%s; Expires=%s", uuid, ngx.cookie_time(ngx.time() + 86400 * 1000))
    ngx.header["Set-Cookie"] = mycookie
    ngx.header["Location"] = request_uri
    ngx.exit(302) 
end

这里另一个有趣的地方是,可以直接通过读取文件 “/proc/sys/kernel/random/uuid”
来生成一个uuid

3) 其它

由于强制要求必须携带cookie信息才能访问后端服务,这种做法其实能起到一定的反爬效果。
注意 旧版本的openresty可能不支持上面的写法,可以升级到最新版本解决。

3. 效果

3.1 浏览器

image_1crgq6h7dqqn1t2i1ipg1u241gsb9.png-69.4kB

经过测试,Chorme/Safari/IE9 兼容良好。

3.2 CURL

不跟踪302跳转

╰─$ curl -v https://vearne.cc/archives/709
*   Trying 207.226.143.150...
* Connected to vearne.cc (207.226.143.150) port 80 (#0)
> GET /archives/709 HTTP/1.1
> Host: vearne.cc
> User-Agent: curl/7.46.0
> Accept: */*
>
< HTTP/1.1 302 Moved Temporarily
< Server: openresty/1.13.6.2
< Date: Mon, 05 Nov 2018 02:04:50 GMT
< Content-Type: text/html
< Content-Length: 167
< Connection: keep-alive
< Set-Cookie: UT_ID=f9b4f4d0-64cd-4750-9267-9ded161fc48d; Expires=Sun, 01-Aug-21 02:04:50 GMT
< Location: /archives/709
<
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>openresty/1.13.6.2</center>
</body>
</html>
* Connection #0 to host vearne.cc left intact

跟踪302跳转

╰─$ curl -L  https://vearne.cc/archives/709
curl: (47) Maximum (50) redirects followed

curl经过多次302跳转, 最终退出。

参考资料

  1. 情景linux–如何获取一个UUID

请我喝瓶饮料

微信支付码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据