HowTo: Configure WordPress To Use A Content Delivery Network (CDN)

by on April 2, 2010 · 48 comments· LAST UPDATED February 20, 2011

in , ,

Research shows that if your web pages take longer than 5 seconds to load, you lose 50% of your viewers and sales. You can speed up your wordpress blog by using a CDN to display content to users faster and more efficiently. You can distributes common files or content such as css, javascript, uploaded images, videos and much more through a CDN, which serves the content from the closest cdn edge server to the end-user. In this tutorial, I will explains how to configure WordPress, Apache/Lighttpd webserver, Bind dns server to use a CDN to distribute your common files such as css, js, user uploaded files and lighten load on your web server.

What Is A CDN?

A content delivery network or content distribution network (CDN) is a system of computers containing copies of data, placed at various points in a network so as to maximize bandwidth for access to the data from clients throughout the network. A client accesses a copy of the data near to the client, as opposed to all clients accessing the same central server, so as to avoid bottleneck near that server. A cdn will increase speed and efficiency for your blog.

What Are The Advantages Of Using CDN Over Central Server?

  • Speed - All common media files distributed via CDN. For example, files.cyberciti.biz configured as CDN subdomain. Everything hosted on files.cyberciti.biz is geographically closer to the end-user. If you run dns query over files.cyberciti.biz, it will return an IP geographically closer to you.
    $ host files.cyberciti.biz
    $ ping files.cyberciti.biz
  • This will increase delivery speed and avoids network congestion on your own server.

  • Security - It adds additional level of security.
  • Availability - CDNs offers 100% availability, even with large power, network or hardware outages.

Different Types Of CDNs

A CDN can use various methods to distribute your content such as:

  1. Peer to peer CDN - This is used to distribute latest episode of a soap opera (movies / TV shows) or some sort of software patch/update in short period of time to large number of users.
  2. Origin Pull CDN - This is useful to distribute small files such as javascript, css, images, text, pdf, .doc, .xls etc. This is recommended for WordPress. All content is stored on your own server called "Origin Pull Host". This host is then registered with the CDN. When the first user requests the content, it is pulled to the CDN network from your host and delivered via CDN to the closest point to that end user. The content is cached on CDN with a TTL (or max age and Etags is also used). This kind of configuration requires storage on your own server and not on the CDN server. The first requesting user has an average CDN experience, while later users have very fast user delivery experience. This is recommended for file size <= 10MB.
  3. PoP Pull CDN - You need to upload content to the CDN host server, where it is stored for delivery. This option is little expensive as you need to purchase the CDN storage with provider along with bandwidth. This is recommend for large files and video streaming etc. You need to upload files to the CDN server using FTP / SCP or API.

Content Delivery Service Providers

A list of some of the larger content delivery network providers. Do your own research before purchasing CDN service from any one of the following provider:

Our Sample Setup

  • Blog URL : http://nixcraft.in/ - This is hosted on your own server using Apache, Lighttpd, IIS or Nginx.
  • Origin Pull URL : http://www-origin.nixcraft.in/ - This is hosted on your own server. You need to configure your web server, wordpress and dns server to use this. This is called as "Origin Pull Host" which is a CDN method by which content is pulled from your web server.
  • CDN URL : http://files.nixcraft.in/ - This is a cdn url hosted by one of the above CDN provider. This url always point to an edge server via proprietor DNS hacks. files.nixcraft.in must be set as CNAME records which will point to domain names of CDN server.
  • CDN DNS CNAME : files.nixcraft.in.example.com - example.com is one of the above CDN provider. This is must be set as CNAME for files.nixcraft.in

Step # 1: Purchase CDN Service

The cost varies between CDN providers. Check CDN service providers website for more information. Next, you need to use service providers "control panel" to configure an "Origin Pull Host" for each domain. In other words configure files.nixcraft.in in origin pull mode. The control panel will also provide your an option to setup CDN dns CNAME. You need to use same CNAME in step # 2. Once the configuration is active and the CNAME is resolving, calls to files.nixcraft.in will be cached from www-origin.nixcraft.in.

Step # 2: Update Your DNS Server

Assuming that you are using BIND dns server edit your zone file and add entry as follows:

; CDN CNAME mapping for files.nixcraft.in
files                3660       IN CNAME files.nixcraft.in.example.com.
; Your www-origin url (note nixcraft.in is also hosted on same server IP 123.1.2.3)
www-origin      3600       IN A 123.1.2.3

Reload your named:
# rndc reload

To keep your configuration simple use same web server for origin pull domain and main domain i.e. host both www-origin.nixcraft.in and nixcraft.in on same web server. This allows you to directly upload and map files to the CDN server.

Please note that you can setup CNAME and origin host names using your ISPs DNS control panel too.

Step # 3: Configure Origin Pull Web Server

You need to configure www-origin.nixcraft.in as follows:

  • Origin pull DocumentRoot: /home/httpd/www-origin.nixcraft.in - All your .css, .js and uploaded files are hosted here.
  • Server Blog DocumentRoot: /home/httpd/nixcraft.in - All your wordpress files are hosted here.
  • MaxAge: Set cache-lifetime headers for static files for cdn network.
  • Etags: An ETag (entity tag) is part of HTTP, the protocol for the World Wide Web. It is a response header that may be returned by an HTTP/1.1 compliant web server and is used to determine change in content at a given URL. When a new HTTP response contains the same ETag as an older HTTP response, the client can conclude that the content is the same without further downloading.

Here is a sample Lighttpd lighttpd.conf entry for the same:

# Configure ETags
etag.use-inode = "enable"
etag.use-mtime = "enable"
etag.use-size = "enable"
static-file.etags = "enable"
 
###### CDN FILES via WordPress Upload ##############
$HTTP["host"]  == "www-origin.nixcraft.in"{
        server.document-root = "/home/httpd/www-origin.nixcraft.in"
        accesslog.filename         = "/var/log/lighttpd/cdn.access.log"
	#  Set max age
        $HTTP["url"] =~ "^/" {
            expire.url = ( "" => "access 60 days" )
        }
}

Here is a sample Apache httpd.conf file:

<VirtualHost www-origin.nixcraft.in>
	ServerAdmin webmaster@nixcraft.in
	DocumentRoot /home/httpd/www-origin.nixcraft.in
	ServerName files.nixcraft.in
	ServerAlias file.nixcraft.in
	ErrorLog /var/logs/httpd/cdn-error_log
	CustomLog /var/logs/httpd/cdn-access_log common
 
	# Files in this directory will be cached for 1 week only.
	# After 1 week, CDN server will check if the contents has been modified or not.
	# If not modified, Apache will send 304 "Not Modified" header
	<Directory "/userimages">
		Header set Cache-Control "max-age=604800, must-revalidate"
	</Directory>
 
	# Disable ETag as we are on cluster Apache server
	<Directory "/pdfs">
		Header unset ETag
		FileETag None
	</Directory>
 
	# Do not cache
	<Directory "/patches">
		Header Set Cache-Control "max-age=0, no-store"
	</Directory>
</VirtualHost>

Step # 4: Configure WordPress To Upload Files To CDN Server

  1. Visit your wordpress dashboard url (e.g., http://nixcraft.in/wp-admin/)
  2. Click on Settings > Miscellaneous Settings
  3. Update it as follows to point out to our configuration paths and CDN domains
Fig.01: Wordrpess Miscellaneous Settings - Set CDN URLS

Fig.01: Wordrpess Miscellaneous Settings - Set CDN URLS

All your uploaded files are saved on your server at /home/httpd/www-origin.nixcraft.in directory. Which is mapped to CDN via origin pull method. In this example:

  • A user requests for http://files.nixcraft.in/uploads/2010/04/test.png
  • First pulled from http://www-origin.nixcraft.in/uploads/2010/04/test.png by your CDN server
  • It is cached at CDN server for 60 days (or as per max age rule)
  • Rest of all user gets image from the CDN server.

Step # 5: Configure WordPress Theme To Serve CSS / JS From The CDN Server

First, copy your .css, and .js files to /home/httpd/www-origin.nixcraft.in directory:

mkdir -p /home/httpd/www-origin.nixcraft.in/{css,js}
cp -av /home/httpd/nixcraft.in/wp-content/themes/mythemename/*.css /home/httpd/www-origin.nixcraft.in/css
cp -av /home/httpd/nixcraft.in/wp-content/themes/mythemename/*.js /home/httpd/www-origin.nixcraft.in/js

Finally, edit your theme (header.php and footer.php) to point to CDN location for stylesheet and/or .js files by visiting "Manage Themes" option from the wordpress dashboard:

 
 
<link rel="stylesheet" href="http://files.nixcraft.in/css/style.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="http://files.nixcraft.in/css/images.css" type="text/css" media="screen, projection" />
 
 

Results

The end result is pretty nice. Here are sample website load speed upgrades after using a CDN:

Fig.02: Alexa Showing Website loading speed

Fig.02: Alexa Showing Website loading speed

Fig.03: Pingdom Tools Showing Website loading speed

Fig.03: Pingdom Tools Showing Website loading speed

How Do I Test Images And Other Media Files Are Cached Or Not By CDN?

Use curl to test HTTP headers (look for Etags, max-age and Expires headers):
$ curl -I http://files.nixcraft.in/css/styles.css
$ curl -I http://files.nixcraft.in/uploades/2010/04/test.png

Sample outputs:

HTTP/1.1 200 OK
Content-Type: image/png
Accept-Ranges: bytes
ETag: "1482142335"
Last-Modified: Fri, 02 Apr 2010 09:11:53 GMT
Content-Length: 33143
Server: lighttpd
Cache-Control: max-age=2588785
Expires: Sun, 02 May 2010 09:13:50 GMT
Date: Fri, 02 Apr 2010 10:07:25 GMT
Connection: keep-alive

A Note About WordPress CDN Plugins

You can automate last two steps with the help of worpdress plugins. However, you need to configure DNS and web server max age to gain fine control.

Recommend readings:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 48 comments… read them below or add one }

1 Kyros Koh April 2, 2010 at 10:59 am

Nice tutorial on the configuration! :)

Reply

2 GatoLinux April 2, 2010 at 2:46 pm

It’s really useful. I tried it two years ago with Amazon and it really speeds the website. I built a smaller CDN using VPS distributed around the whole world and I got satisfactory results, too.

Reply

3 Willie Jackson April 2, 2010 at 3:16 pm

Hi Vivek-

Thanks for taking the time to write all of this. I use the W3 Total Cache plugin to integrate a CDN with my site using this method, but I’ll still probably to some etag tweaking in my Apache conf files.

Reply

4 PrinceOfAndalus April 2, 2010 at 3:25 pm

now, i know how big website speed up their internet website,
tq nixcraft

Reply

5 James D Grey April 2, 2010 at 3:36 pm

I did this for a web project that a client had me do. Being a Python developer and primarily working with Django I understood how these things work in a very different context. After fighting with this for an hour I opted to go with this plugin, which happens to do all of these things:

http://wordpress.org/extend/plugins/w3-total-cache/

Far less sysadmin, far more productive. :)

Reply

6 Swpsm April 2, 2010 at 4:13 pm

Thanks Vivek!

I got w3-total-cache and I don’t think so it has an option to configure DNS, max-age and Etags thingy. Though it has its own additional set of options. Nevertheless, this tutorial and plugins both are handy!

Reply

7 Frederick Townes April 2, 2010 at 4:19 pm

For feeds, pages and posts, W3 Total Cache (WordPress users only) automatically configures cache-control, etags and expires based on your settings. More options will appear in later versions. W3 Total Cache also supports all of the CDN types discussed in this very helpful post.

Reply

8 Joe April 2, 2010 at 4:26 pm

Can we get a tutorial for VBulletin based board?

Reply

9 Vamsi April 3, 2010 at 10:39 am

Hi,
what if the CDN providers uses Anycast technology ??

Reply

10 nixCraft April 3, 2010 at 10:46 am

Anycast does plays role to select path to the “nearest” cdn edge server. However, this is done via CNAME itself so you don’t have to worry about anything else.

Reply

11 nixCraft April 6, 2010 at 11:31 am

@Joe,

The first 3 steps are same for any web app including VBulletin forum software. You need to modify VBulletin templates (styles) to point to cdn. You may also need to modify style code to change path for user uploaded files and other media.

Reply

12 ntx April 8, 2010 at 11:39 pm

You can also do a mixture of hosting yourself and put things to a CDN (e.g. for very popular or frequently accessed files).

Or e.g. if you allow image uploading and you want to process the files locally. You might also want to serve them directly thereafter and there is no time to upload them to a CDN first. Instead a cron-job to puts your files to amazon´s S3.

http://redmine.lighttpd.net/projects/lighttpd/wiki/Absoluation#other-solutions

This uses mod_magnet to check if a file is locally available and serve it, if not, redirect to your CDN, might be useful to some of you.

Reply

13 Vamsi April 19, 2010 at 5:40 am

Hi ,
I got syntax error message for “Header set Cache-Control “max-age=604800, must-revalidate”..

“apache2 :We failed to correctly shutdown apache, so we’re now killing all running apache processes. This is almost certainly suboptimal, so please make sure your system is working as you’d expect now! (warning).
… waiting Syntax error on line 69 of /etc/apache2/sites-enabled/000-default:
Invalid command ‘Header’, perhaps misspelled or defined by a module not included in the server configuration
failed!

Reply

14 Subhajit Dey September 6, 2010 at 10:13 am

it’s 2 good ….
;-)

Reply

15 Zeeshan September 6, 2010 at 10:38 am

Please write the same guide for Joomla that will be very useful

Zeeshan

Reply

16 takizo September 7, 2010 at 1:02 am

great tips bro. But what CDN server do you recommend, for the entry level?

Reply

17 Katie @ women magazine October 4, 2010 at 3:21 pm

I am having a small website hosted on a shared server but someone told that using CSN might do little wonders for such sites. The site is having very small traffic of 15K per month. What sort of CDN would you propose for me and why?

Reply

18 jaysunn October 9, 2010 at 3:27 pm

We used to use edgecast to backbone a very large new york city website , sites. I recommend them to others.

@vivek,
Well done my friend.

jaysunn

Reply

19 fre wp themes October 17, 2010 at 7:30 pm

Nice article, I am a big time fan of your site, keep up the nice work, and I will be a frequent visitor for a very long time.

Reply

20 Curtis November 1, 2010 at 5:14 am

Excellent article as usual, thank you !

Reply

21 aftab alam November 14, 2010 at 11:41 pm

same thing i am looking for to test my gallery blog.
i have a question..
you missed a important point for already running wp sites. as like mine.,

as you said, i try on my site but changing the upload folder settings in wp admin, my existing images are not showing. bcoz of changes in upload folder, you got my point?

have you any solution for existing images that are set in our old posts?

Reply

22 nixCraft November 15, 2010 at 8:10 am

I’ve not tested this but one can write direct sql quires against wp DB (for img src html tags) to replace example.com/uploads/2010/01 to point to cdn.example.com

Reply

23 aftab alam November 15, 2010 at 11:28 am

thanks Vivek for your reply…
i think this is the important part of setting up CDN for existing wp blog with images stored in default wp-content folder.
if you know or test this, pleas share with us and it will be helpful for others like me who are interested in to set cdn for their wp powered sites.

Reply

24 nixCraft November 15, 2010 at 9:08 pm

You can write sql query using php or any other P* language to replace http://www.example.com/blog/wp-content/uploads/2010/11/demo.gif to http://cdn.example.com/wp-content/uploads/2010/11/demo.gif. This need to be run against wp_posts table. Backup your database before playing with fire ;) and you need to use php function preg_replace() for this purpose. Another alternative is to use “W3 Total Cache” plugin which claims to do the same thing. Keep an eye on our feed and I might come with some simple solution.

Reply

25 aftab alam November 15, 2010 at 9:49 pm

working on my site http://models-hq.com for this purpose…
i need a .htaccess file for old urls that google and other search engines already indexed. 301 permanent redirection required for this purpose.

pleas suggest me to 301 redirect code for old url to new url on subdomain.

Reply

26 nima0102 November 21, 2010 at 7:13 am

Thanks a lot for this GOOOOOD article.

Reply

27 Kevin December 10, 2010 at 1:25 am

Very thorough and comprehensive write-up! But you forgot to include our CDN in your providers list :) We integrate super quickly and easily with Wordpress thanks to Frederick’s W3 Total Cache Plugin. Anyone still looking for a cost-effective Wordpress CDN solution I’d recommend checking out: http://www.maxcdn.com/wordpress-cdn/

Reply

28 Jim December 12, 2010 at 11:04 am

Kevin. spamming is the best way to attract new clients .

Reply

29 Bob May 3, 2011 at 12:47 pm

Thanks – very interesting.

My bluehost site is quite slow even though I have optimized as much as I can. I was thinking of purchasing a static ip address for my site, but I now wonder whether opting to pay for cdn storage will make my site faster than a static ip address?

Reply

30 Mike June 10, 2011 at 3:33 am

Static IP address is not going to make your website any faster. Moving to something like a virtual server, or something that dedicated resources to you will make it quicker. but a dedicated IP will not make your site quicker.

CDN in this case would make your site a bit quicker.

Reply

31 Peter May 20, 2013 at 2:02 pm

Hi Mike,
very interesting. I haven’t known jet, that static IP address is not going to make my website any faster.
Thanks

Reply

32 Fernando July 2, 2011 at 10:07 pm

Nice tutorial.

Finally i can upload my files from wordpress directly to CND.

Just a question. The upload limit now is 2mb but on my php config its seted to 64mb.
How can i increase it?

Thank you and good job

Reply

33 nixCraft July 2, 2011 at 10:11 pm
34 Rance September 16, 2011 at 10:36 pm

New plugin just released called Speed Cache is available that does the same thing using Edgecast. No fancy configuration(s) are needed, the plugin does all of the configuring and it works great! http://wordpress.org/extend/plugins/speedcache/

Reply

35 Erick December 3, 2011 at 12:07 am

If I use CloudFlare, do I still need these CDN type things?

Reply

36 John January 3, 2012 at 4:13 am

nice tips, easy steps to learn.. thanks for sharing

Reply

37 Martie February 7, 2012 at 6:36 am

I think the VaultPress crew will palrbboy do this once the project exits beta. (which is hopefully soon so I can back up 3 other blogs!)

Reply

38 itmg February 8, 2012 at 5:03 pm

Great tips, thanks for sharing. This is something I wanted to setup

Reply

39 Kyle February 25, 2012 at 4:11 pm

Thanks for sharing this configure wordpress. I will keep visiting your website.

Reply

40 Chris June 9, 2012 at 7:01 pm

Great article. Another link to consider which is popular in the wordpress community:
http://www.maxcdn.com/features/integrations/wordpress-cdn-module/

Reply

41 Pothi Kalimuthu July 12, 2012 at 9:02 am
42 Cricketbook October 1, 2012 at 9:50 am

Hmmm very nice tutorial thankx for sharing

Reply

43 Sankar December 26, 2012 at 11:59 am

this is great article….Thank you.

Reply

44 Qaiser January 22, 2013 at 6:23 am

very nice article, explained the process in detail, I thought configuring CDN will be an automatic process through any plugin but seems like i will have to struggle a bit. and this post will surely help men.. thanks again

Reply

45 Taha February 19, 2013 at 12:02 pm

I do not have Miscellaneous settings.

Reply

46 Ankit July 7, 2013 at 4:28 pm

1) Whats the difference btwn Push CDN and Pull CDN and when to use which.. 2) How a 301 permanent redirection of site will be affected while using CDN??

Reply

47 Yogesh Singh August 3, 2014 at 6:57 am

Is it possible to load the CSS/Js at the backend of Wordpress to load from CDN too?

Reply

48 vikram September 5, 2014 at 9:45 am

Sir,

The header file upload option isn’t coming in my wordpress blog…
How can i solve this
Whether i have to rectify from server side or from Wordpress blog

Urgent

Reply

Leave a Comment

Tagged as: , , , , , , , , , , ,

Previous post:

Next post: