Adding a favicon

A “favicon” is an icon used by browsers for tabs and bookmarks. This helpsto distinguish your website and to give it a unique brand.

A common question is how to add a favicon to a Flask application. First, ofcourse, you need an icon. It should be 16 × 16 pixels and in the ICO fileformat. This is not a requirement but a de-facto standard supported by allrelevant browsers. Put the icon in your static directory asfavicon.ico.

Now, to get browsers to find your icon, the correct way is to add a linktag in your HTML. So, for example:

  1. <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">

That’s all you need for most browsers, however some really old ones do notsupport this standard. The old de-facto standard is to serve this file,with this name, at the website root. If your application is not mounted atthe root path of the domain you either need to configure the web server toserve the icon at the root or if you can’t do that you’re out of luck. Ifhowever your application is the root you can simply route a redirect:

  1. app.add_url_rule('/favicon.ico',
  2. redirect_to=url_for('static', filename='favicon.ico'))

If you want to save the extra redirect request you can also write a viewusing send_from_directory():

  1. import os
  2. from flask import send_from_directory
  3.  
  4. @app.route('/favicon.ico')
  5. def favicon():
  6. return send_from_directory(os.path.join(app.root_path, 'static'),
  7. 'favicon.ico', mimetype='image/vnd.microsoft.icon')

We can leave out the explicit mimetype and it will be guessed, but we mayas well specify it to avoid the extra guessing, as it will always be thesame.

The above will serve the icon via your application and if possible it’sbetter to configure your dedicated web server to serve it; refer to theweb server’s documentation.

See also