Skip to content
Advertisement

SVG sprite file – is it necessary for it to have “.svg” extension, or is php/nothing ok so long as the content type header is set correctly?

I have a PHP script that generates my SVG sprite on the fly. Naturally that file ends in .php, not .svg.

I’m setting the Content-type at the top of the script with header('Content-type: image/svg+xml');

I have nginx set up in such a way that php extensions are optional, so I can now reference my svg icons with:

<use href="/icons#svg-save-icon" xlink:href="/icons#svg-save-icon" x="0" y="0"></use>

Is that ok? It works in the browsers I’ve tested it in – I just don’t know if I’m missing out on some browser optimisation because it can’t “guess” as to the content-type before it retrieves the file.

As an aside, I also have these caching headers set up, does this look right for a year-long far future expiry?

header('Cache-Control: public, max-age=31536000');
header_remove('Pragma');
header_remove('Set-Cookie');
header_remove('Expires');
header('Accept-Ranges: bytes');

Advertisement

Answer

You are correct, the Content-Type header is all that matters.

In general, browsers don’t see URLs as breaking down into parts like “directory”, “filename”, and “extension”; in fact, HTTP has no concept of “files” at all. Rather, a URL is just a string to be sent to some server; the server then responds with some content, and a header indicating how that content should be interpreted.

Whether you reference your SVG as /icons, or /icons.php, or /icons.awesome, the browser will just send that URL, and have no idea if the response is coming from a file with that name, or a different name, or generated on demand.

You can see this in action on this very page: the URL doesn’t end “.html”, but the browser is rendering the HTML. That’s not relying on some default built into the browser, it’s because the Content-Type header that Stack Overflow’s server sent identified the returned content as text/html.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement