Using Cloudflare as CDN for Rails applications (2024)

We use Cloudflare as our DNS server. But,Cloudflare is much more than a DNS server. It can be used as a content deliverynetwork (CDN).

A CDN is a geographically distributed group of servers that cache content closeto end users. Let's say that a user from London is hitting a website that has aJavaScript file hosted in Chicago. That JavaScript file has to travel all theway from Chicago to London. This means the site will load slowly.

A CDN will have a copy of that JavaScript file in London itself. In this way forthat user, that JavaScript file will be loaded from the London server and notfrom the Chicago server. This is what a CDN primarily does.

Here's how we set up Cloudflare as a CDN for our Rails applications.

1. Configure CNAME record for CDN subdomain in Cloudflare

We need a subdomain that will act as a CDN. ForNeetoCal, we use https://cdn.neetocal.com asthe subdomain. You can use any subdomain you want.

To set up this subdomain, we need to follow these steps.

  1. Add a new record with the type CNAME.
  2. In the name field, enter *.
  3. In the target field, enter the URL where the Rails app is deployed.

If we already have a CNAME record for * that handles all the subdomains,then we don't need to create a new one.

Using Cloudflare as CDN for Rails applications (1)

2. Turn on the Proxy feature in Cloudflare

In the previous step, when creating a new CNAME record, by default, Cloudflarewill enable proxy for each record.

Once the Proxy status column is turned on, it will display 'Proxied' asshown below.

Using Cloudflare as CDN for Rails applications (2)

When we turn on "Proxy", then the DNS queries will resolve to the Cloudflare IPaddress instead of the target. It means Cloudflare will get all the requests andthen Cloudflare in turn will forward those requests to the target.

Let's say that a user from Paris loads a webpage which is hosted in Chicago andCloudflare has a server in Paris. When "Proxy" is turned on, then when the usermakes the first request to the server, that request will go to Cloudflare.Cloudflare doesn't have the JavaScript file, so Cloudflare will forward thatrequest to the server. The server will send that JavaScript file to Cloudflare.Cloudflare will cache this JavaScript file and serve the JavaScript file to theuser.

Two seconds later, another user from a different part of Paris hits the samewebpage. This time, Cloudflare has a cached copy of the JavaScript file andCloudflare will serve the JavaScript from the server in Paris itself.

This has two benefits. The first benefit is that the user gets to see thewebpage really fast. The second benefit is that the server cost is a lot lowersince fewer requests need to be served by the server in Chicago.

What all things Cloudflare can cache

Cloudflare can only cache files that are stored on the domain that is proxiedthrough Cloudflare. If we have an image file that is stored on Amazon S3 and isaccessed via a direct S3 URL, then Cloudflare won't be able to cache it.

Cloudflare caches are based on file extension and not by MIME type.Hereis the list of file extensions that will be cached by default. HTML is not onthis list.

Cloudflare allows us to cache other file types by setting up suitablepage rules.

3. Set appropriate Cache-Control headers in Rails

When utilizing Cloudflare as a CDN, it's crucial to configure our Rails app toserve assets with specific Cache-Control headers. This ensures optimal cachingbehavior for resources.

The Rails app should serve assets with a header similar to the one given below.

1cache-control: public, max-age=31536000

The cache-control must be public and max-age must be a positive value forCloudflare tocache the resource.

For this, we need to modify the Rails configuration fileconfig/environments/production.rb.

1config.public_file_server.headers = {2 'Cache-Control' => 'public, max-age=31536000'3}

Here, Cache-Control is set to 'public', allowing any cache (includingCloudflare) to store the resource. The max-age is specified as 31,536,000seconds (one year), indicating how long the cache should retain the objectbefore considering it stale.

4. Configure asset_host in Rails.

We added the secrets for the asset_host in our Rails application'sconfig/secrets.yml file.

1production:2 asset_host: <%= ENV["ASSET_HOST"] %>

We also added an environment variable called ASSET_HOST that contains our newCDN host URL.

1ASSET_HOST=cdn.neetoX.com

Once this is done all asset URLs will point to https://cdn.neetoX.com.

5. Verify changes

Once all the setup is done, it can take a few hours for the changes to bereflected. Hit the page and see the response header of .js file.

If the response header cf-cache-status had a value of HIT then that meansCloudflare is serving that asset from its cache.

Using Cloudflare as CDN for Rails applications (3)

Using Cloudflare as CDN for Rails applications (2024)
Top Articles
Scarcity Mindset: Causes and How To Overcome It
7 Facts About Divorce After a Long-Term Marriage | Iafrate & Salassa, P.C. | Birmingham Divorce Lawyers
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5388

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.