nosequeldeebee nosequeldeebee - 1 year ago 118
HTTP Question

Preventing browser Caching by setting Headers in Go not working

I'm trying to prevent users from going back to the login page after logging in by accessing their browser cache.

Here is my handler for the login page in


http.HandleFunc("/login", login)

After login the user gets directed to
and the handler is also in

http.HandleFunc("/", serveHtml)

in my
function I've tried to set the headers to prevent caching:

func login(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Expires", time.Unix(0, 0).Format(http.TimeFormat))
w.Header().Set("Pragma", "no-cache")
w.Header().Set("X-Accel-Expires", "0")
//... the rest of my login code here. Upon successful login redirects to "/"

There are no problems when the
page is loaded again (either through a logout redirect or if for some reason the user intentionally visits the login page). I expire the Cookie and everything behaves normally.

But I'm trying to prevent the user from hitting the Back button after login and accessing their browser cache to get back to the login page. I thought setting the headers in my
function as suggested by some other answers on SO would prevent the browser from caching the login page.

But that doesn't work and the user can still hit the Back button and access the login page from their browser cache after logging in.

How do I set the headers correctly to prevent browser caching of the login page?

Answer Source

So after several days of reading about setting browser headers, I've figured this out.

@Volker's comment about this not being a Go specific question was kind of right.

There were no issues with actually setting the browser headers in my login function above.

The reason users could still hit the back button and get to the cached login page was because I didn't have https enabled on my site.

Page must be delivered over HTTPS, otherwise this cache-busting won't be reliable.

After installing an SSL Certificate and switching to http.ListenAndServeTLS the cache busting works correctly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download