HowTo: Host SPA Project on Raspberry Pi (using Nginx server)

Nginx is another type of server that is very commonly used with modern server technologies. It is usually considered faster than the Apache server, and it also has better support for SPA web technologies than the PHP applications. It is suitable for serving applications from Raspberry Pi because of its optimal use of memory and CPU usage. Again, don’t expect it to be able to host a real-time live website, but it can surely help to test out how hosting works on Linux platforms and can surely handle a few simultaneous users. Before we start installing Nginx, let’s update the Raspberry Pi using the following command:

sudo apt-get update && apt-get upgrade -y
Installation

Presuming you don’t have any other server pre-installed on the system, let’s start installing the Nginx server using the following command.

sudo apt-get install nginx -y

and that should do it, after the server has been installed, we just need to make sure that we can see the default page, by trying out the IP of the device into the browser of any device in the network. If you don’t know the IP of the Raspberry Pi, try the following:

hostname -I

You should be able to view the following page

Configuration

At this point, the server has been perfectly configured for an HTML, CSS, and Javascript website, but to host a SPA, we need to make a few modifications to the server configuration. Nginx utilizes server blocks to host multiple domains on a single server, this file needs to be notified regarding the application routing. It can be achieved in the following ways:

sudo nano /etc/nginx/sites-enabled/default

and add the following block of code:

server
{
     listen 80;
     listen [::] 80;
     server_name www.abcd.com abcd.com;
     root /var/www/html;
     index index.html;
     location / 
    {
         try_files $uri$args $uri$args/ /index.html;
    }
}

Next, we need to copy the compiled angular code to the “/var/www/html” location (Learn more about Linux Directories). After the code has been copied to this location, just restart the Nginx server and you should be ready to go.

sudo systemctl restart nginx

To make your application available in a secured network, you can follow this article. To make the same application available over the internet, follow this article.

Uninstalling

To uninstall the Nginx server try the following command

sudo apt-get remove nginx nginx-common -y
sudo apt-get purge nginx nginx-common -y
sudo apt-get autoremove -y

Leave a Comment