Virtual hosting is a method of publishing multiple websites on a single server. This allows servers to share resources such as memory and processor cycles with the published services. The given term stands widely for web servers. But the principles can be applied to other Internet services as well. One of the most common applications is shared web hosting. As the prices are lower than a dedicated server, and they can host many clients on one server. In the last blog we discussed installing Nginx, today we are going to see how to publish multiple websites with Nginx Web Server.
With the Nginx web server, you can use the same server resources for different sites. A single web server instance can publish multiple websites. Define it in the conf file with the URL and the IP address of your VPS. After the request is made, the traffic will be handled by the document root.
Host Multiple Websites With Nginx Web Server
So in this guide, we are going to use server blocks to encapsulate configuration details and host multiple domains from a single server. We will set up a domain called demo.com. By default, Nginx on Ubuntu 20.04 has a server block configured to serve documents from directories under /var/www/html. This works well for one site but can get unwieldy when hosting multiple sites. Instead of modifying /var/www/html, we will create the demo.com site’s directory structure within /var/www and /var/www/ as the default directory to be served.
Firstly, create a directory for demo.com with the given command, hence the request made for demo.com will be served from the /var/www/demo.com directory.
# mkdir -p /var/www/demo.com
Next, we are going to create an index.html page using vi or your favorite editor. Run the given command in terminal
# vi /var/www/html/demo.com/index.html
After that enter the given command into the file and save it using :wq
<title>www.demo.com</title> <h1>Welcome to www.demo.com!</h1> </html>
Next, open the Nginx .conf and add the following using the given command.
# vi /etc/nginx/nginx.conf
Save the .conf file.
server {
listen 80;
root /var/www/html/demo.com;
index index.html;
server_name demo.com;
location / {
try_files $uri $uri/ =404;
}
Now the Nginx Server will listen on port 80 for the website demo.com. You can check the conf file regarding any syntax error by running the given command in the terminal.
# nginx -t
Next restart the server using the given command. After that open your Internet browser and type in http://demo.com to reach the index page.
# systemctl restart nginx
Conclusion
In brief with Virtual hosting, you can use the server resources more efficiently. A VPS server provides a composite virtual host for your website. Host an unlimited number of business websites on one server. Handle requests from defined URLs. This tutorial went through the steps of hosting multiple websites with the Nginx web server. This can be done with Apache too.