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
Private Equity Fees: Management & Performance Fees | Moonfare
Meta (META) stock forecast and price prediction
Netronline Taxes
Victor Spizzirri Linkedin
Warren Ohio Craigslist
Trevor Goodwin Obituary St Cloud
12 Rue Gotlib 21St Arrondissem*nt
Practical Magic 123Movies
Bustle Daily Horoscope
Rainfall Map Oklahoma
What’s the Difference Between Cash Flow and Profit?
Used Wood Cook Stoves For Sale Craigslist
Everything You Need to Know About Holly by Stephen King
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Leeks — A Dirty Little Secret (Ingredient)
Craiglist Kpr
使用 RHEL 8 时的注意事项 | Red Hat Product Documentation
Uta Kinesiology Advising
The Blind Showtimes Near Amc Merchants Crossing 16
Stoney's Pizza & Gaming Parlor Danville Menu
67-72 Chevy Truck Parts Craigslist
Www Va Lottery Com Result
2000 Ford F-150 for sale - Scottsdale, AZ - craigslist
Margaret Shelton Jeopardy Age
10 Best Quotes From Venom (2018)
WOODSTOCK CELEBRATES 50 YEARS WITH COMPREHENSIVE 38-CD DELUXE BOXED SET | Rhino
County Cricket Championship, day one - scores, radio commentary & live text
R/Orangetheory
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Emiri's Adventures
Wbli Playlist
Tenant Vs. Occupant: Is There Really A Difference Between Them?
Oreillys Federal And Evans
AsROck Q1900B ITX und Ramverträglichkeit
Build-A-Team: Putting together the best Cathedral basketball team
Toonily The Carry
World History Kazwire
Frcp 47
Metro Pcs Forest City Iowa
Differential Diagnosis
Foxxequeen
Gli italiani buttano sempre più cibo, quasi 7 etti a settimana (a testa)
What is a lifetime maximum benefit? | healthinsurance.org
New Zero Turn Mowers For Sale Near Me
De boeken van Val McDermid op volgorde
Roller Znen ZN50QT-E
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Epower Raley's
What Responsibilities Are Listed In Duties 2 3 And 4
Ranking 134 college football teams after Week 1, from Georgia to Temple
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.