Skip to content

Instantly share code, notes, and snippets.

@sjain07
Last active October 13, 2017 17:54
Show Gist options
  • Save sjain07/4025065a214ecdac7657693b47943b5e to your computer and use it in GitHub Desktop.
Save sjain07/4025065a214ecdac7657693b47943b5e to your computer and use it in GitHub Desktop.
Url shortener using nginx and lua
events {}
http {
upstream pgdb {
postgres_server urlshortnertestdb.cccccccccccc.us-west-2.rds.amazonaws.com dbname=redirect user=root password=password;
}
server {
listen 80;
server_name localhost;
location /admin/ {
uwsgi_pass unix:///tmp/uwsgi.sock;
include /home/ubuntu/urlshortner/server_files/conf/uwsgi_params;
}
location ~ "^/([0-9a-zA-Z]{18})\/{0,1}$" {
content_by_lua '
local query_string = string.gsub(ngx.var.request_uri, "/", "");
local referer = ngx.var.http_referer;
local res = ngx.location.capture("/lookup",
{ args = { query = query_string } }
);
ngx.location.capture("/increment",
{ args = { query = query_string } }
);
ngx.location.capture("/log",
{ args = { query = query_string } }
);
ngx.redirect(res.body);
';
}
location /lookup {
internal;
postgres_pass pgdb;
postgres_escape $esc_uid $arg_query;
postgres_query GET "SELECT \"Output\" FROM \"Redirect_redirecturl\" WHERE \"Input\" = $esc_uid;";
postgres_output text;
}
location /log {
internal;
postgres_pass pgdb;
postgres_escape $esc_uid $arg_query;
postgres_escape $referencia $http_referer;
postgres_escape $user_agent $http_user_agent;
postgres_query GET "INSERT INTO \"Redirect_visit\" (\"Created\",\"RedirectUrl_id\",\"Referer\",\"UserAgent\") SELECT now(), ID, $referencia, $user_agent FROM \"Redirect_redirecturl\" WHERE \"Input\" = $esc_uid;";
}
location /increment {
internal;
postgres_pass pgdb;
postgres_escape $esc_uid $arg_query;
postgres_query GET "UPDATE \"Redirect_redirecturl\" SET \"Counter\" = \"Counter\" + 1 WHERE \"Input\" = $esc_uid;";
postgres_output none;
}
location ~ ^/add {
postgres_pass pgdb;
rds_json on;
postgres_escape $url $arg_url;
postgres_query GET "INSERT INTO redirect_redirecturl (input, output) VALUES((SELECT substring(md5(random()::text||$url), 0, 5)), $url) RETURNING input;";
postgres_output text;
postgres_rewrite GET changes 201;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment