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

Posted on in Categories Apache, lighttpd, Networking last updated July 2, 2016

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, configured as CDN subdomain. Everything hosted on is geographically closer to the end-user. If you run dns query over, it will return an IP geographically closer to you.
    $ host
    $ ping
  • 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 : – This is hosted on your own server using Apache, Lighttpd, IIS or Nginx.
  • Origin Pull URL : – 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 : – 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. must be set as CNAME records which will point to domain names of CDN server.
  • CDN DNS CNAME : – is one of the above CDN provider. This is must be set as CNAME for

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 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 will be cached from

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                3660       IN CNAME
; Your www-origin url (note is also hosted on same server IP
www-origin      3600       IN A

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 and 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 as follows:

  • Origin pull DocumentRoot: /home/httpd/ – All your .css, .js and uploaded files are hosted here.
  • Server Blog DocumentRoot: /home/httpd/ – 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"]  == ""{
        server.document-root = "/home/httpd/"
        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:

	ServerAdmin [email protected]
	DocumentRoot /home/httpd/
	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"
	# Disable ETag as we are on cluster Apache server
	<Directory "/pdfs">
		Header unset ETag
		FileETag None
	# Do not cache 
	<Directory "/patches">
		Header Set Cache-Control "max-age=0, no-store"

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

  1. Visit your wordpress dashboard url (e.g.,
  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/ directory. Which is mapped to CDN via origin pull method. In this example:

  • A user requests for
  • First pulled from 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/ directory:

mkdir -p /home/httpd/{css,js}
cp -av /home/httpd/*.css /home/httpd/
cp -av /home/httpd/*.js /home/httpd/

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="" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="" type="text/css" media="screen, projection" />


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
$ curl -I

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:

49 comment

  1. 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.

  2. 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.

  3. 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:

    Far less sysadmin, far more productive. :)

  4. 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!

  5. 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.

  6. 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.

  7. @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.

  8. 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.

    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.

  9. 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

  10. 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?

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

    Well done my friend.


  12. 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?

  13. 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.

    1. You can write sql query using php or any other P* language to replace to 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.

  14. working on my site 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.

  15. 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:

  16. 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?

    1. 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.

  17. 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

  18. 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

  19. 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??

  20. 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


Leave a Comment