Automatically Trigger Git Pull For Website On Github Push

Serving your site from a git "working directory" is considered bad practice - see reasons here and here.

The best way to do this is to set up a "bare" git repo on your server with a "post-receive" hook. This article is what I followed when I did this recently, the basic idea is:

  1. Create a "bare" repo with git init --bare

  2. Edit hooks/post-receive in your bare repo to copy the repo to your web root: GIT_WORK_TREE=/var/www/yoursite git checkout -f

  3. On your local machine add the bare repo as a remote.

  4. Use git push <remotename> to push to your live site.


Okay have managed to figure this one out. Turns out there is no native feature in Git to trigger a remote fetch (as in pushing code to the repository and having the repository trigger a pull origin on the web server).

The way I have resolved this was to upload a PHP script to my web server under the default vhost. Within that file I have it set to run shell_exec("cd /path/to/my/site/root" && sudo git pull origin master". It is then set to send me an email with the message output through STDOUT to inform me if the pull was completed successfully or not.

I have then set Github up with a webhook so that every push to the repository will trigger a webhook call to the file which I simply have addressed as http://server.domain.com/github-deploy.php.

There are presently some undisclosed security checks I perform to make sure that no one else can access the file and in time I will probably add IP checks to make sure that requests to the file only come from IP's in Github's address block.

An important note that I should add here is that the only way to make this work is to allow the apache user access as a sudoer on the server but limit it to being able to run the sudo command to launch Git otherwise an access denied message will be triggered. By restricting it to git though and not passing any input from the calling script into the shel_exec command I believe I have been able to offset any concerns over security.

Eventually I will probably implement this as a service link with Github but for now this is ample.