Home » Web Design and Development » Website Hosting » Hosting a static website with Nginx on Ubuntu

Hosting a static website with Nginx on Ubuntu

In our previous post “What is Nginx and how to install Nginx on Ubuntu 20.04 ?”, we mentioned how you can setup the Nginx server. In this post, we will detail, how you can host your first website with Nginx.

Note: To execute this steps, you will need root access or “Sudo” permissions.

Make sure that nginx is properly setup and running using,

$ sudo systemctl status nginx

Nginx by default runs on /var/www/html directory which you can verify from “/etc/nginx/sites-available/default” file,

server {
        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;
}

and when you type “http://localhost” on your browser, you can see either of the index.html webpage opened in your browser.

Now, we can create a new directory inside /var/www/html/helloworld-nginx/ and create a simple helloworld.html as,

$ sudo mkdir /var/www/html/helloworld-nginx/
$ sudo vim /var/www/html/helloworld-nginx/helloworld.html
<html>
  <head>
  </head>
  <body>
  <h1>Hello, World of nginx...</h1>
  </body>
</html>

Settings up Virtual Host

Above, we just copied/written our web code, now we need to inform / configure nginx, so it can start serving the web pages from our code on the browser. For this we need to write the virtual host configuration files as, ( The default /etc/nginx/sites-available/default file also have a example for your reference )

$ sudo vim /etc/nginx/sites-enabled/helloworld
erver {
       listen 8080;
       listen [::]:8080;

       server_name helloworld.com;

       root /var/www/html/helloworld-nginx;
       index index.html;

       location / {
               try_files $uri $uri/ =404;
       }
}
  • listen The port where your nginx server will be listening for this website
  • root is a directory where we have placed our website’s .html file. 
  • index is used to specify file available when visiting root directory of site. 
  • server_name can be any as per your domain name. This will work only on live servers where you have properly configured DNS settings to point the domain name to your hosting server where you are running nginx.

Restart the nginx server as,

$ sudo service nginx restart

Now, you should see that your static website with simple index.html is getting served in browser by visiting http://localhost:8081/ and you would see the html page with following text,

Hello, World of nginx…


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment