Railsã§èªåã®ãµã¼ãåãç¥ããã¨ãã¦request.host_with_portã使ããã¨ãã¦ãå¤æ®µreverse proxyä¸ã ã£ãã®ã§ããã©ããªãã¨ã«ãªã£ãã
Rails(Rack)ã ã¨
def host_with_port if forwarded = @env["HTTP_X_FORWARDED_HOST"] forwarded.split(/,\s?/).last else @env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}" end end
ã¨ãªã£ã¦ãã¦X-Forwarded-Hostããããããã°ããã®æå¾ã®å¤ãå©ç¨ãããã¨ãã¦ãããX-Forwarded-Hostã¯proxyãåãåã£ãHostããããæ¬å½ã®å®å ã«éãããã(éæ¨æº)ã以ä¸ã®ãããªå¤æ®µproxyã®å ´å
client -> proxy1 -> proxy2 -> ... -> proxyN -> server
serverãåãåãX-Forwarded-Hostã¯
proxy1, proxy2, ..., proxyN
ã¨ããå½¢å¼ã«ãªãã
ãã®ãããhost_with_portã¯proxyNãè¿ãã®ã ããã¡ãã¨ãã¦ã¯proxy1ãå¤ããè¦ãããã¹ãåãªã®ã§proxy1ãè¿ãã¦ã»ããã
ã¢ããªå´ã¯ããããªãã£ãã®ã§Apacheã®è¨å®ã§ç¡çç¢çproxyNããµã¼ãã«
Host: proxy1
ã¨éãããã«ãããã©ã
ãªãã§æå¾ãè¿ãã®ããããããããã£ã¦ã¿ãããã£ã±ãããããªã
ãè¦ã¦redirectããã¾ãããããã«ã¨ãããã¨ã¿ããã ãã©ããredirectã®å ´åãproxy1ãè¿ãã¦ã»ããæ°ãããã
ã§ä»ã®ãã¬ã¼ã ã¯ã¼ã¯ã¯ã©ãã ããã¨æã£ã¦ã¡ãã£ã¨ããã¹ã¦ã¿ã
Django
def get_host(self): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in self.META): host = self.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in self.META: host = self.META['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = self.META['SERVER_NAME'] server_port = str(self.META['SERVER_PORT']) if server_port != ('443' if self.is_secure() else '80'): host = '%s:%s' % (host, server_port)
è¨å®ã§USE_X_FORWARDED_HOSTãæå¹ã«ãã¦ããå ´åã®ã¿X-Forwarded-Hostãå©ç¨ãã¦ãããããã«ã¤ãã¦ã¯ä»¥ä¸ã§è°è«ããã¦ãã
確ãã«X-Forwarded-Hostãã©ãã¾ã§ä¿¡ç¨ãã¹ããªã®ãã¨ãã話ãããããforward proxyã®æ å ±ãåé¤ããã¦ããªãå ´åã¯ã©ãããã®ã¨ããããããããã¾ããã¬ã¼ã ã¯ã¼ã¯ãããã°ã£ã¦ããããããªãæ°ãããã
ãã¨ãè¤æ°å¤ããå ´åã«ã¯å¯¾å¿ãã¦ããªãã£ã½ã
Plack
sub _uri_base { my $self = shift; my $env = $self->env; my $uri = ($env->{'psgi.url_scheme'} || "http") . "://" . ($env->{HTTP_HOST} || (($env->{SERVER_NAME} || "") . ":" . ($env->{SERVER_PORT} || 80))) . ($env->{SCRIPT_NAME} || '/'); return $uri; }
X-Forwarded-Hostã¯å©ç¨ãã¦ããªãã¿ããã
ã¾ã¨ã
ã¾ããX-Forwarded-Hostã¯ãã¬ã¼ã ã¯ã¼ã¯ã«ãã£ã¦ã¯å¯¾å¿ãã¦ããªãããããã¾ãä¿¡ç¨ãã¹ãã§ããªãã