Git post-receive hook for deployment of a static site

Using a post receive hook for website deployment
Other deployment methods
Firstly, let’s mention that there are other potentially easier ways to do this type of deployment. A Github action or using a service such a Netlify can do the build and deployment for you.
How to do this
This approach is a lower level approach where all you need need is SSH access to the webserver you are hosting the site on.
Let’s say that we use a static site generator to build our website. The build process creates the static site in a public
directory in the root of the repo.
Usually the default would be to configure the public
generated site to be ignored by git. For this process we would need to include the generated site.
Directory structure on your webserver
We will use the home directory of the user account you are using to SSH (so it has permissions to access the required files).
We will create a git directory and a bare repo for our site.
# Change to home directory
cd ~
# Create a tmp directory to be used later
mkdir tmp
# Create git directory and change into it
mkdir git
cd git
# Initialise a bare repo
git init --bare
You will see a directory structure created which should contain a hooks
directory.
The hook’s shell script
In the hooks directory we will create a post-receive
hook script.
cd hooks
touch post-receive
chmod +x post-receive
Then paste the contents of the following script in there. Replace the <username>
with the username that you will SSH to the server.
#!/bin/bash
unset GIT_DIR
set GIT_DIR .
# Change into your bare repo
cd /home/<username>/git/
# Set the work tree (the files in the repo) to the temp directory we created
git --work-tree=/home/<username>/tmp checkout -f
# Sync the files in the public directory of the repo to the root of the Nginx webserver
rsync -r /home/<username>/tmp/public/ /var/www/html
Add your webserver as a git remote
The repository on your local machine will have an origin remote (assuming you started by creating it on a remote git server like Github). You will need to add a remote which points to your webserver.
git remote add webserver ssh://<username>@<server>:<ssh-port>//home/<username>/git
Deploying change to the site
When you have changes to your site build to the public
directory you can deploy them to the server using:
git push webserver master