{
	auto_https off
	admin off
}

:{$PORT} {
	root * {$MESSAGES_FRONTEND_ROOT:/app}
	header -Server

	route {
		# Health checks
		respond /__lbheartbeat__ 200
		respond /__lbheartbeat__/ 200

		reverse_proxy /__heartbeat__/* {$MESSAGES_FRONTEND_BACKEND_SERVER:localhost:8000} {
			header_up X-Forwarded-Proto https
			header_up X-Forwarded-For {remote_host}
		}

		# Django backend proxy
		reverse_proxy /api/* {$MESSAGES_FRONTEND_BACKEND_SERVER:localhost:8000} {
			header_up X-Forwarded-Proto https
			header_up X-Forwarded-For {remote_host}
		}

		redir /{$DJANGO_ADMIN_URL:admin} /{$DJANGO_ADMIN_URL:admin}/ 301

		reverse_proxy /{$DJANGO_ADMIN_URL:admin}/* {$MESSAGES_FRONTEND_BACKEND_SERVER:localhost:8000} {
			header_up X-Forwarded-Proto https
			header_up X-Forwarded-For {remote_host}
		}

		reverse_proxy /static/* {$MESSAGES_FRONTEND_BACKEND_SERVER:localhost:8000} {
			header_up X-Forwarded-Proto https
			header_up X-Forwarded-For {remote_host}
		}

		# Next.js static export routes
		@mailbox path_regexp ^/mailbox/[^/]+$
		rewrite @mailbox /mailbox/[mailboxId].html

		@mailbox_thread path_regexp ^/mailbox/[^/]+/thread/[^/]+$
		rewrite @mailbox_thread /mailbox/[mailboxId]/thread/[threadId].html

		@mailbox_new path_regexp ^/mailbox/[^/]+/new$
		rewrite @mailbox_new /mailbox/[mailboxId]/new.html

		@domain_root path /domain
		rewrite @domain_root /domain.html

		@domain_id path_regexp ^/domain/[^/]+$
		rewrite @domain_id /domain/[maildomainId].html

		@domain_dns path_regexp ^/domain/[^/]+/dns$
		rewrite @domain_dns /domain/[maildomainId]/dns.html

		@domain_signatures path_regexp ^/domain/[^/]+/signatures$
		rewrite @domain_signatures /domain/[maildomainId]/signatures.html

		# Default: SPA fallback
		try_files {path} /index.html
		file_server
	}

	handle_errors {
		rewrite * /404.html
		file_server
	}
}
