Set up a Reverse Proxy of Google Fonts

Protect visitors' privacy. So easy.

As said in this post, using web fonts is a good way to beautify your site and improve user experience. However, it usually comes with dependence on third-party services (e.g. Google Fonts), which causes privacy issues. A simple yet good way is to set up a reverse proxy of such services, so that visitors do not send direct requests to these third-party, and their privacy is protected.

How to?

Just add some configuration in your web server. Take NGINX and Google Fonts as example.

First, you should carefully watch how Google Fonts CSS works. Let's assume you use Roboto Regular 400 font, and you should get some HTML like this:

<link
  href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
  rel="stylesheet"
/>

Open that link, and you should see a list of @font-face, whose src directives all start with https://fonts.gstatic.com/s/. So, the solution is quite easy now. Just use the following NGINX config.

http {
  server {
    listen xxx;
    server_name fonts.example.com;
    location /s/ {
      proxy_pass https://fonts.gstatic.com;
    }
    location / {
      proxy_pass https://fonts.googleapis.com;
      proxy_set_header Accept-Encoding '';
      sub_filter https://fonts.gstatic.com '';
      sub_filter_once off;
      sub_filter_types *;
    }
  }
}

And use this HTML:

<link
  href="https://fonts.example.com/css2?family=Roboto&display=swap"
  rel="stylesheet"
/>

Note that this directive proxy_set_header Accept-Encoding ''; is to make Google's response CSS plain without compression, so that sub_filter can work.

To better protect visitors' privacy, you may need to use proxy_set_header and proxy_hide_header directives to clear some headers visitors send and Google responds.