Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

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');
question from:https://stackoverflow.com/questions/65951148/svg-sprite-file-is-it-necessary-for-it-to-have-svg-extension-or-is-php-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...