server {
	# workaround that!
	resolver 192.168.222.1;

	listen   8008;
	server_name  khm0.google.com *.google.com;

	# enable to debug
	log_not_found off;

	access_log /var/log/nginx/gmap-cache.access_log main;
	error_log /var/log/nginx/gmap-cache.error_log warn;
	log_format googlog '[$time_local] "$host" "$request" $status $body_bytes_sent';

	recursive_error_pages on;

	location / {
		return 404;
	}

	location = /favicon.ico {
		access_log off;
		empty_gif;
	}

	location = /_NONEXISTENT_ {
		internal;
		access_log  /var/log/nginx/gmap-cache-neghit.access.log googlog;
		return 404;
	}

	set $ro_root /var/gmap-cache;

	location = /_FIXME_ {
		internal;
		access_log off;
		root $ro_root;
		rewrite ^.*$ /invalidimg.png break;
	}

	location = /kh {
		access_log  /var/log/nginx/gmap-cache-hit.access.log googlog;

		root $ro_root;
		error_page 404 = @cache;

		set $cachename "";
		if ($args ~ '^n=404&v=2[012345678](?:&hl=(?:en|ru))?(?:&cookie=[^&]*)?&t=([trsq]+)$') {
			set $cachename $1;
		}

		if ($cachename = "") {
			rewrite ^.*$ /_FIXME_ last;
		}

		set $realpath "";
		if ($cachename ~ '^([trsq]{12})([trsq]{2})?([trsq]{2})?([trsq]{2})?([trsq]{1,2})?$') {
			# The best resolution:
			# trtrsqrqqtts ts st tr q t
			set $realpath /$1/$2/$3/$4/$1$2$3$4$5.jpeg;
			set $tile $1;
			set $deep $5;
		}

		if ($realpath = "") {
			return 404; # goto @cache
		}

		set $local_and_deep "";
		if ($deep ~ '^[trsq]{2}$') {
			set $local_and_deep "1";
		}
		if (-d "$ro_root/$tile") {
			set $local_and_deep "1${local_and_deep}";
		}
		if ($local_and_deep = "11") {
			rewrite ^.*$ /_NONEXISTENT_ last;
		}

		if ($realpath) {
			rewrite ^.*$ $realpath break;
		}

		return 404;
	}

	location @cache {
		internal;
		access_log  /var/log/nginx/gmap-cache-halfhit.access.log googlog;
		root /var/tmp/nginx/maps.google.com;
		error_page 404 = @fetch;

		rewrite ^.*$ /$cachename.jpeg break;
	}

	location @fetch {
		internal;
		access_log  /var/log/nginx/gmap-cache-miss.access.log googlog;

		# proxy_temp_path       /var/tmp/nginx/proxy;
		proxy_store             /var/tmp/nginx/maps.google.com/$cachename.jpeg;
		proxy_store_access      user:rw  group:r  all:r;

		# should I fallback to kh0 ?
		# rewrite     ^.*$  "x${request_uri}x" break;
		proxy_pass        http://$host$request_uri;

	}
}

