nginx-自建docker-hub-代理


####################################
log_format format_hub_example_com '[$time_iso8601] [$http_host] [$remote_addr] [$uri] $status $body_bytes_sent "$request" "$http_referer" "$http_user_agent" ';
####################################
# 使用 map 来匹配和替换 upstream 头部中的 auth.docker.io
map $upstream_http_www_authenticate $m_www_authenticate_replaced {
    "~auth\.docker\.io(.*)" "$1";
    default "";
}

map $m_www_authenticate_replaced $m_final_replaced {
    "~(.*)" 'Bearer realm=\"$scheme://$host$1';
    default "";
}

server
{
 	####################################	
 	server_name hub.example.com;
 	####################################	
 	listen 0.0.0.0:80;
 	listen 0.0.0.0:443 ssl http2 ; 
 	ssl_certificate          /code/hub_example_com-full.crt;
 	ssl_certificate_key	 /code/hub_example_com-full.key;
 	####################################	
 	if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {		set $year $1;		set $month $2;		set $day $3;	}
 	access_log  /code/hub_example_com.access.$year-$month-$day.log format_hub_example_com ;  	
        error_log   /code/hub_example_com.error.log;
 	####################################	
	# listen 443 ssl http2;
	# 改成自己的域名
	# server_name xxxx.example.com;

	# 证书部分
	# ssl_certificate 证书地址;
	# ssl_certificate_key 密钥地址;

	ssl_session_timeout 24h;

	# TLS 版本控制
	ssl_protocols TLSv1.2 TLSv1.3;
	ssl_prefer_server_ciphers on;      
	ssl_ciphers TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:EECDH+CHACHA20:EECDH+AESGCM:EECDH+AES;

	proxy_ssl_server_name on;

	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_set_header X-Forwarded-Proto $scheme;

	# 修改jwt授权地址
	proxy_hide_header www-authenticate;
	add_header www-authenticate "$m_final_replaced" always;

	# 关闭缓存
	proxy_buffering off;
	# 转发认证相关
	proxy_set_header Authorization $http_authorization;
	proxy_pass_header  Authorization;

	# 对 upstream 状态码检查,实现 error_page 错误重定向
	proxy_intercept_errors on;
	recursive_error_pages on;
	# 根据状态码执行对应操作,以下为301、302、307状态码都会触发
	error_page 301 302 307 = @handle_redirect;

	# v1 api
	location /v1 {
		proxy_pass https://index.docker.io;
		proxy_set_header Host index.docker.io;
	}

	# v2 api
	location /v2 {
		proxy_pass https://index.docker.io;
		proxy_set_header Host index.docker.io;
	}

	# jwt授权地址
	location /token {
		proxy_pass https://auth.docker.io;
		proxy_set_header Host auth.docker.io;
	}

	location / {
		# Docker hub 的官方镜像仓库
		proxy_pass https://registry-1.docker.io;
		proxy_set_header Host registry-1.docker.io;
	}
	
	#处理重定向
	location @handle_redirect {
		resolver 1.1.1.1;
		set $saved_redirect_location '$upstream_http_location';
		proxy_pass $saved_redirect_location;
	}
}