There will be a time in your life where you want to set nginx up to serve all of your static content. Then you’ll get fancy with your programming and want to serve dynamic content. Heres the thing, you don’t want all of your requests to be served dynamically. You want the front facing web server to serve up your static content, while still letting connections through to your dynamic content engine. I’m going to show you how to do it. In our case, we’re using connect-vhoster in combination with node.js, connect and spark to serve dynamic content. Let’s get into the nitty gritty:
I want mine to work with wild card subdomains so i can set up anything on the fly. The nginx.conf I’m about to explain already has support for that, but you’ll need to make sure that you set up wild card DNS with your DNS host first.
In your nginx.conf we need a server block (this goes at the end of the http block) Here is mine:
server {
listen 80;
server_name ~^(?<domain>.*techosaur.us);
root /var/webapps/vhosts/$host/public/;
try_files $uri $uri/ @nodevhost;
location @nodevhost {
access_log /var/log/nginx/vps-access-log;
proxy_pass http://localhost:3001;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_max_temp_file_size 0;
}
}
So there it is. It’s neat, it’s clean, and it’s not very descriptive. I’ll explain it line by line:
server 80;
This just tells nginx to listen on the standard http port of 80.
server_name ~^(?<domain>.*techosaur.us);
This sets server_name to whatever the wild card subdomain of the moment is. It’s totally dynamic and very smooth.
root /var/webapps/vhosts/$host/public/;
Here we set the root of the site of the moment to the correct directory based on the subdomain ($host). For example, if we’re being accessed on lollerskates.techosaur.us then $host is set to lollerskates.techosaur.us. If you’re using the connect middleware vhost module that I do (and I think you should), then your directory names in /var/webapps/vhosts match the subdomains that you want to use. This is a key part of letting nginx serve static files for your wild card subdomains. Without this, nginx won’t be able to find the files.
try_files $uri $uri/ @nodevhost;
This is the most important part of nginx static file serving. This line tries to serve $uri (/something/whatever.html) from the root that we defined above, if that doesn’t work it’ll try it with a / on the end, and if that doesn’t work then it’s probably a dynamic page and will and it off to location @nodevhost, which is our reverse proxy.
I’m going to skim over the location @nodevhost block because this is covered elsewhere, but essentially it’s just a reverse proxy to localhost on port 3001 which is the port that my vhost module listens on. We forward some headers in the 2nd part which allow the vhosts to see the real remote IP instead of nginx’s IP.
And that’s about it
