Before we begin, ensure that you have:
- Access to a VPS running Linux (e.g., Ubuntu).
- Git and a static site generator (Hugo or Jekyll) installed on your VPS.
- A Git repository for your static website, preferably on GitHub or GitLab.
1. VPS Configuration
First, log in to your VPS and create a directory for your project if it doesn't already exist. This directory will serve as the local repository on your server.
mkdir -p /var/www/mywebsite
cd /var/www/mywebsite
git init --bare
2. Setting Up Git Hook
Inside the repository on your server, navigate to the hooks
directory and create a post-receive
file. This hook will execute after each successful reception of changes into the server repository.
cd /var/www/mywebsite/hooks
nano post-receive
Insert the following script into the post-receive
file (for Hugo or Jekyll depending on your preference) to ensure the generation of static pages and their copying into the web server's public directory.
For Hugo:
#!/bin/bash
GIT_REPO=/var/www/mywebsite
TMP_GIT_CLONE=/tmp/mywebsite
PUBLIC_WWW=/var/www/HTML/mywebsite
git clone $GIT_REPO $TMP_GIT_CLONE
cd $TMP_GIT_CLONE
hugo
rsync -av --delete public/ $PUBLIC_WWW
rm -rf $TMP_GIT_CLONE
For Jekyll:
#!/bin/bash
GIT_REPO=/var/www/mywebsite
TMP_GIT_CLONE=/tmp/mywebsite
PUBLIC_WWW=/var/www/html/mywebsite
git clone $GIT_REPO $TMP_GIT_CLONE
cd $TMP_GIT_CLONE
jekyll build
rsync -av --delete _site/ $PUBLIC_WWW
rm -rf $TMP_GIT_CLONE
Grant executable permissions to the script:
chmod +x post-receive
3. Client-Side Configuration
On your local machine, add a remote repository pointing to the VPS.
git remote add vps [user]@[server-address]:/var/www/mywebsite
Now, whenever you want to deploy changes to the production server, simply push the changes to the remote repository on your VPS
git push vps master
Automating the deployment of static websites using Git hooks on a VPS enables developers to publish changes easily and quickly without manual intervention. With Hugo or Jekyll, you can generate up-to-date versions of your site directly on the production server, simplifying the deployment process and keeping your website constantly updated.