This guide will help you to setup your own git enabled website. Let’s say that I have a web server on tar.ninja. tar.ninja will also own a git repository that stores the website files. Furthermore, when you have a change to the website, once you run git push the server’s website will automatically update.

This is possible because on the server-side, git has hooks that are called on different git operations (These hooks also exist on the client side as well but we will only be using server-side hooks.) These hooks are stored under repo_location/hooks. One of which is called after a git push this is the post-receive hook. You can look into the other hooks here.

Create the Git User

On the web server, create a user for the git that will store the git repository for your site. You probably would run:

useradd -m -s /bin/bash git

I recommend not setting a password. If you don’t set one, password authentication will be disabled. You can “log in” by running sudo su git or using ssh keys.

Now log into the git user. Add the ssh keys for users you want to have access to the git repository in .ssh/authorized_keys.

Create the Git Repository

Make the repository directory.

mkdir example.com

Initialize it.

git init --bare

Now add the git hook. Create the file example.com/hooks/post-receive and fill it with the following. Change REPO_NAME to the name of you website. Every push will put the website in /home/git/web/$REPO_NAME.

#!/bin/sh -l
REPO_NAME=example.com
GIT_REPO=$HOME/$REPO_NAME.git
TMP_GIT_CLONE=/tmp/git/$REPO_NAME
PUBLIC_WWW=$HOME/web/$REPO_NAME

# clone into a usable repo
git clone $GIT_REPO $TMP_GIT_CLONE
# remove the .git directory.  a hacker could use this to know the history of your website
rm -Rf $TMP_GIT_CLONE/.git
# replace the old website
rm -Rf $PUBLIC_WWW
cp -R  $TMP_GIT_CLONE $PUBLIC_WWW
# remove the temporary clone
rm -Rf $TMP_GIT_CLONE

exit

Link the git user’s web directory to the actual web directory.

This varies from setup to setup. This is something that you have to figure out. But since I use mailinabox for my web, all of my websites are located under /home/user-data/www/<site_name>. So I would link the entire git web directory (/home/git/web) to /home/user-data/www.

ln -s /home/git/web/ /home/user-data/www

Add some content

Now clone the repository on another computer whose public key was added to the git user’s .ssh/authorized_keys.

git clone git@example.com:example.com
# Now to add content.
echo "Hello :)" > index.html
# Add change
git add .
git commit -m "Initial test"
# push it
git push

The should see stuff on your website now :)