A client has a group of 6 or so servers that provide some php based applications. In order to reduce the load on Apache (number of concurrent threads), we thought that it would be a good idea to move static content (images, css, javascript, etc) off onto another server. Past experience indicates that NGINX might be a good choice for this. It became clear that managing the static content on this new server was going to be a little challenging. Suppose we have 3 application servers and want to use the same static content server for all of them – we need to find a way to divide the content up, one way would be to keep the content for each of the application servers in a different folder and change the URLs to reflect that:
http://static.company.com/app1/foo.css
http://static.company.com/app2/bar.jpg
http://static.company.com/app3/moo.js
While this would work, we have to go back and change all the paths in the application to add the folder and manage the content in the folders. Annoying and not very portable. Another thought was to use a different virtual server in NGINX for each application server:
http://app1-static.company.com/foo.css
http://app2-static.company.com/bar.jpg
http://app3-static.company.com/moo.js
Then we create CNAME records for each that makes app1-static a CNAME for static. Now we can just change the hostname in the URL for the static content. We put the hostname for the static content in the config for the application. The path portion stays the same.
Now the problem becomes maintaining the static content. In the SVN repository for the application, the static content is maintained along side the rest of the application. In a developer mode, the static content server can be set to the same machine as the application server. How do we maintain just the static content in the virtual machines on the static content server? Answer; we don’t. Make the static content server a caching proxy server instead and get the content from the application server, cache it and deliver it to the end user. In the NGINX config, we can make it a caching proxy for just our hosts. Say we have app1, app2 and app3 application servers and the static content CNAME records app1-static, app2-static and app3-static, we can use the following in the NGINX config:
if ($host ~* (.*)-static\.company\.com) {
set $host $1;
}
proxy_pass http://$host.company.com;
As long as we have our CNAME pointing to this static content server with the hostname format like shown, it will fetch, cache and deliver our stuff for us. We don’t have to worry about keeping the files on the static content server up to date with the apps. Tweaking the other cache settings depend on how often you want to refresh the cache and how large the cache can be, etc.