-
-
Save noff/865d3d043964d099b927 to your computer and use it in GitHub Desktop.
nginx sharding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
server { | |
listen 80; | |
listen 443 ssl; | |
server_name api.domain.com; | |
keepalive_timeout 5; | |
root /home/rails/api.domain.com/current; | |
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; | |
ssl_certificate /etc/nginx/ssl/domain.com.chained.crt; | |
ssl_certificate_key /etc/nginx/ssl/domain.key; | |
access_log /var/log/nginx/api.domain.com-access.log; | |
error_log /var/log/nginx/api.domain.com-error.log warn; | |
error_page 500 502 503 504 /500.html; | |
location ~ ^/(assets|images|javascripts|stylesheets|system|favicon\.ico|robots\.txt)/ { | |
return 444; | |
} | |
location / { | |
try_files $uri @app; | |
add_header Access-Control-Allow-Credentials true; | |
add_header Access-Control-Allow-Origin $http_origin; | |
} | |
location @app { | |
perl ' | |
sub { | |
my $r = shift; | |
my $request_shop_id = ""; | |
if ($r->request_method eq "GET") { | |
if($r->args =~ /shop_id=([a-z0-9A-Z]+)/ ) { | |
my $shop_id = "$1"; | |
my $shard_id = find_shard($shop_id); | |
if($shard_id ne "") { | |
$r->internal_redirect("/shard" . $shard_id . $r->uri . "?" . $r->args); | |
return; | |
} | |
} | |
$r->internal_redirect("/shard_not_found"); | |
} else { | |
$r->has_request_body(\&post); | |
} | |
}; | |
sub post { | |
my $r = shift; | |
if( $r->request_body ne "" && $r->request_body =~ /shop_id=([a-z0-9A-Z]+)/ ) { | |
my $shop_id = "$1"; | |
my $shard_id = find_shard($shop_id); | |
if($shard_id ne "") { | |
$r->internal_redirect("/shard" . $shard_id . $r->uri . "?" . $r->args); | |
return; | |
} | |
} | |
$r->internal_redirect("/shard_not_found"); | |
}; | |
sub find_shard { | |
my $shop_id = shift; | |
open(my $fh, "<", "/home/rails/nginx_shop_mapping.conf") or die("cant open filename"); | |
while(my $row = <$fh>) { | |
chomp $row; | |
if($row ne "") { | |
@parts = split / /, $row; | |
if(@parts[0] eq $shop_id) { | |
close $fh; | |
return $parts[1]; | |
} | |
} | |
} | |
close $fh; | |
return ""; | |
} | |
'; | |
} | |
location /shard0 { | |
rewrite /shard0(.*) $1 break; | |
proxy_pass http://api-0; | |
proxy_redirect off; | |
include /etc/nginx/api_proxy_params.conf; | |
} | |
location /shard1 { | |
rewrite /shard1(.*) $1 break; | |
proxy_pass http://api-1; | |
proxy_redirect off; | |
include /etc/nginx/api_proxy_params.conf; | |
} | |
location /shard_not_found { | |
return 403; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment