Multiple virtual hosts with Nginx
When we develop web applications, we have to test on our local boxes firstly. In this case it always comes in handy if we could use a web server to serve the application just like we plan to use on production server. When we have many apps, a step further, when we want them talking to each other, we will have to use virtual hosts. And this is quite simple in nginx.
Here’s one simple config file for 2 virtual hosts in nginx.
Now let’s break it down.
Firstly is the top-level block, we are defining a http server, which has many default settings, the served types, gzip setting and such. All these you can find in official manual.
The most important part is the code below.
Here we defined two virtual hosts.
- Both of them listen to port 80,
- check the requested server with
server_name
, if matched, process it. - then it should deliver result from
root
with content ofindex
In this above example we only serve 2 static pages, but you more or less get the idea how the structure of this config should look like.
What if we actually want to serve few dynamic sites? Of course that’s also possbile! Inside each server block you need to tell nginx how should it talk to your apps, for example with following php app running with php-fpm:
Here we let nginx talk to php-fpm with unix-socket, for example in app1:
Above are just simple settings for 2 apps, you can extend them to your usage and make several apps running at same time on your machine :) Please leave a comment if you have any question!