HowTo: Host SPA project on Raspberry Pi (using Apache server)

Apache is one of the most used servers, not only because of the cost but also for being feature-rich for decades. Not only is application development easy for Apache but it has proved itself from time to time to be reliable, safe, and fast for most web applications. For this reason, being able to run it on the Raspberry Pi is a great achievement. Although it is not recommended to run live websites, it surely can serve a finite number of test users for the small hardware. To start with we will update the operating system itself by using the following command.

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

Before moving on, make sure you don’t have any other server installed on the Pi to avoid any conflicts with the application source directory. Once sure, you can install the Apache web server by using the following command:

sudo apt-get install apache2 -y

Once done, you can just try to browse using the Pi IP into any device connected over the local network. If you don’t know the IP of the device you can find it out by typing in the following command on the device:

Hostname -I

Once you have the IP address, you should be able to view the default index page provided by the Apache server as below

Configuration

Once you can see a page like the above, you can be sure that the server has been installed correctly. At this point, the server is completely configured if you just want to host an HTML, CSS, and JavaScript website, but if you want to host any SPA application, we need to make a few modifications. You go to the default directory web directory, “/var/www/html” (Learn more about Linux Directories). There you enter the following command to create “.htaccess” file

sudo nano /var/www/html/.htaccess

copy and paste the following code:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

This code makes sure all your requests are redirected to the index.html in that directory. After this, all you need to do is copy the SPA compiled files into this folder, and restart the apache server using the following command:

sudo systemctl restart apache2

In case you are having issues modifying the files in the “/var/www/html” directory, you can try adding your user to the default www-data group created by the Apache installation by executing the following commands:

sudo usermod -a -G www-data [username]
sudo chown -R -f www-data:www-data /var/www/html

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 apache server from your linux distribution use the following commands

sudo apt-get remove apache2 -y
sudo apt-get auto-remove -y

Leave a Comment