diff --git a/server/http.go b/server/http.go
index 6310b1627e3a256d53096d807ca4c78807e5a6e8..30a0c14e34d84c2319d4b4c4c73ef7e9c2f8d124 100644
--- a/server/http.go
+++ b/server/http.go
@@ -330,6 +330,10 @@ type logoutServiceInfo struct {
 
 // Logout handler. We generate a page that triggers child logout
 // requests to all the services the user is logged in to.
+//
+// Unauthenticated requests to /logout will fall through to this
+// handler, but auth.Username will be empty in that case. We are
+// still going to show the logout page to avoid confusion.
 func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request) {
 	auth, ok := login.GetAuth(req.Context())
 	if !ok {
@@ -337,8 +341,6 @@ func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request) {
 		return
 	}
 
-	//
-
 	var svcs []logoutServiceInfo
 	for _, svc := range auth.Services {
 		svcs = append(svcs, logoutServiceInfo{
@@ -354,8 +356,8 @@ func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request) {
 		"IncludeLogoutScripts": true,
 	}
 
-	// Close the keystore.
-	if h.keystore != nil {
+	// Close the keystore (only if the session had a valid username).
+	if h.keystore != nil && auth.Username != "" {
 		var shard string
 		if auth.UserInfo != nil {
 			shard = auth.UserInfo.Shard
diff --git a/server/login/login.go b/server/login/login.go
index fd540fdf48b564ce81a1c12998689535181b38da..5d25d14e6f765e6da58d128346e9c0dacde1757d 100644
--- a/server/login/login.go
+++ b/server/login/login.go
@@ -190,8 +190,10 @@ func (l *Login) ServeHTTP(w http.ResponseWriter, req *http.Request) {
 		// wrapped handler. Note that the Auth object will still
 		// contain valid data, but Authenticated will be set to false.
 		if req.URL.Path == l.urlFor("/logout") {
-			log.Printf("logging out user %s", session.Username)
-			session.Authenticated = false
+			if session.Authenticated {
+				log.Printf("logging out user %s", session.Username)
+				session.Authenticated = false
+			}
 			session.Delete()
 		} else if !session.Authenticated {
 			// Save the current URL in the session for later redirect.