
Hosting Unity WebGL game on Cloudflare Pages for free
Introducing
Recently, I'm so addicted to game developing. It has much more fun than backend developing.
I'd like to share my games on the Internet, but it's too intricate for me to make it published on the app store. Since it's not a 3A game or has to connect a server, and Unity can build webgl game, so I decide to host it on static content hosting service. Pulishing on web page.
Cloudflare Pages
Like Github Pages, Cloudflare Pages is also a static content hosing service. Here is a comparison table.
Cloudflare Pages | Github Pages | |
---|---|---|
Price | Free | Free |
Bandwidth limit | unlimited | 100G/month |
Single file size limit | 25MB | 100MB |
Total file size\amount limit | 20000 files | 1GB |
Private repository | yes | no |
China accessibility | OK | Irregularly blocked |
Cutom domain name | yes | yes |
Response Headers configurable | yes | no |
The "Response Headers configurable" is a very important attribute that determines whether you can or cant enable comprassion when you build your game.
Unity build WebGL
Click File→Build Settings to open the build window.
In the Build Settings window, click Player Settings to open player setting window.
Here, you can config build settings as you like.
Then, you can click Build or Build and Run to start building.
Publishing on Cloudflare Pages
Cloudflare Pages allows you to fetch data from Github repository(Private repo is also suppoted). Or you can upload manually from your computer.
BUT, if you upload Unity builded files directly, you most likely get error message like this.
1 | Unable to load file Build/Build.framework.js.br |
or
1 | Unable to load file Build/Build.framework.js.gz |
or
1 | Unable to parse Build/[File Name].framework.js.br |
Why?
The web server that without configured doesn't know how to provide Content-Type and Content-Encoding response header for br(Brotli compressed file) or gz(Gzip compressed file) file. As a result, the web browser doesn't know how to deal with those files. Since br and gz file is compressed file, they can't be used until decompressed.
And I searched a lot, but there are only two solutions: Turn off compression in Unity or config web server MIME mapping to make it offers response headers correctly.
But, those two solutions don't work for me. After turning compression off, the game size becomes 3 times bigger than the compressed one, exceeding the file size limitation. And for the second solution, obviously, I can't modify any config file on Cloudflare server.
My solution
Since Cloudflare allows us to modify response header by ourself, we can provide the right header manually.
Create a txt file named "_headers"(No extension),and save the contents below to it.
1 | /Build/*.data.gz |
Upload this "_headers" file to your Pages root folder to make it work.
Enjoy