Tuesday, 2 May 2017

Resolving contradictory Cache-Control headers

I am maintaining a Restify server using a static content plugin. The plugin imposes a Cache-Control header despite anything that happened beforehand. max-age is always included, and defaults to 3600.

Cache-Control: public, max-age=3600

I need to have a large max-age for everything except index.html.

server.pre((req, res, next) => {
    const path = url.parse(req.url);
    if (path.pathname === '/' && req.accepts('text/html')) {
        req.url = '/public/index.html';

        // Encourage the client to always download index.html.
        res.header('Expires', new Date(0));
        res.header('Cache-Control',
            'no-store, no-cache, must-revalidate, max-age=0');
    }

    next();
});

The problem is that the static server's forced addition of Cache-Control causes the server to send contradictory headers.

Cache-Control:no-store, no-cache, must-revalidate, max-age=0
Cache-Control:public, max-age=315360000

I tried the below to stop this, but for whatever reason index.html requests 404 using this setup.

server.pre((req, res, next) => {
    // Same as above, except max-age is omitted
});

const directory = path.resolve('.');

const serveDir = restify.serveStatic({
    directory,
    maxAge: (10 * 365 * 24 * 60 * 60),
    gzip: true,
});

const serveIndex = restify.serveStatic({
    directory,
    file: 'index.html',
    maxAge: 0,
    gzip: false
});

server.get(/\/public\/.*/, function(req, res, next) {
    if (req.url === '/public/index.html') {
        serveIndex(req, res, next);
    } else {
        serveDir(req, res, next);
    }
});

My question is a two-parter:

  1. Is this even an issue? I don't know if browsers will resolve the contradiction by downloading index.html fresh (which is what I want)
  2. Assuming the answer to #1 is "yes", why is my attempt to fix the contradiction 404ing index.html?


via Sage Gerard

No comments:

Post a Comment