Nginx As a Front End to Apache
Posted on 21st August 2008 by SameerI’ve been evaluating nginx, a lightweight web server, for the last week and I am coming away impressed. Over the last year or so nginx seems to have overtaken lighttpd for the crown of lightweight web servers.
In our case nginx is used to serve static files while apache is used to serve dynamic content (we also use nginx for simple load balancing). A request for http://www.mysite.com/file.extension will first be sent to nginx which will determine whether to serve the file itself (if its static) or if not it will request the url http://localhost:8080/file.extension from apache and pass back the result seamlessly to the end user.
#nginx configuration
server {
listen 80;
server_name www.mysite.com;
# static files
location ~* ^.+.(jpg|jpeg|gif|png|ico|css|txt|js|htm|html)$ {
root /path/to/webroot;
}
# pass all else onto apache waiting at localhost:8080
location / {
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Setting up Apache is also simple (but make sure to look through httpd.conf and comment out any line similar to “Listen 80″ because nginx and httpd will then both try listen on port 80):
#apache httpd configuration
Listen localhost:8080
<VirtualHost localhost:8080>
DocumentRoot /path/to/webroot
</VirtualHost>
For clarity’s sake I would actually suggest giving your static files their own domain such as “static.mysite.com” so that you don’t need to run a regular expression to determine what files to serve directly from nginx. You would then proxy all requests to “www.mysite.com” to apache. However, the above set up will work out of the box without having to change your software.
[...] a previous post we saw how simple it is to set up nginx in front of apache, and in this post I’ll show you it’s just as easy to use nginx as a load [...]
Sameer
Great post - and excellent way of explaining how to use nginx. I started using apache mod_mem_cache (it’s out of experimental stage) in order to cache the Elgg css and graphics files in memory. Just put this in your mem_cache.conf
CacheEnable mem /_css
CacheEnable mem /_graphics
MCacheSize 4096
MCacheMaxObjectCount 100
MCacheMinObjectSize 1
MCacheMaxObjectSize 2048
Of course as a load balancer - nginx is a great fit for Apache
best regards
Danny Lieberman
In your article you state that you would use static.domain.com for your static content and point that to the document root. One thing about that, what if someone goes to static.domain.com/index.php? Without any regular expression you wouldn’t know if you are serving a PHP file or image. This would easily give someone your source code. Here’s what I have:
server {
listen 80;
server_name static.domain.com;
root /var/www/www.domain.com/public;
}
How would we patch up the security hole there?

