Skip to content

Instantly share code, notes, and snippets.

@antonlukin
Last active May 31, 2021 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonlukin/69a19b2b0b9404e432b1edd9fddd14ff to your computer and use it in GitHub Desktop.
Save antonlukin/69a19b2b0b9404e432b1edd9fddd14ff to your computer and use it in GitHub Desktop.
Parse facebook share counter using nginx with lua extension
location /facebook {
set $token "href=${arg_id}&layout=button_count&locale=en_US";
resolver 1.1.1.1;
proxy_pass https://www.facebook.com/plugins/like.php?$token;
proxy_ignore_headers Expires;
proxy_ignore_headers Cache-Control;
proxy_hide_header Content-Type;
proxy_hide_header Content-Security-Policy;
proxy_hide_header X-content-Type-Options;
proxy_set_header Accept-Encoding "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
lua_need_request_body on;
lua_use_default_type off;
header_filter_by_lua_block {
ngx.header.content_length = nil
}
add_header Content-Type "application/json";
body_filter_by_lua_block {
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. ngx.arg[1]
ngx.arg[1] = nil
if ngx.arg[2] then
local count = ngx.re.match(ngx.ctx.buffered, '>Like</span><span.+?>([^<]+)<', 's')
if count then
ngx.arg[1] = 'knifeFacebookCount({"engagement":{"custom":' .. count[1] .. '}})'
else
ngx.arg[1] = 'knifeFacebookCount({"error":"Facebook parse error"})'
end
end
}
}
@antonlukin
Copy link
Author

Use sudo apt install nginx-extras to install nginx-lua module.
To receive counter follow link http://example.com/facebook-share/?href=https%3A%2F%2Fknife.media%2Fsmells-in-culture%2F

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment