This guide explains how to set up Git on your server to allow updating the website directly from GitHub or your local machine, using the main branch as the default.
Ensure Git is installed by running:
sudo apt update
sudo apt install git
Create a Git repository on the server:
sudo mkdir -p /var/repo/website.git
cd /var/repo/website.git
sudo git init --bare
Set the default branch to main for future repositories:
git config --global init.defaultBranch main
Create a post-receive hook to deploy the site automatically:
nano /var/repo/website.git/hooks/post-receive
Add this content:
#!/bin/bash
GIT_WORK_TREE=/var/www/html git checkout -f main
Then, make it executable:
chmod +x /var/repo/website.git/hooks/post-receive
On your local machine, navigate to your local Git repository and add your server as a remote:
git remote add production ssh://@:/var/repo/website.git
Important: Replace <your-username>
with your server's username (e.g., root
), and <your-server-ip>
with the actual IP address of your server.
After making changes to your local website files, add and commit them. Then push the changes to the main branch on the server:
git add .
git commit -m "Describe your changes"
git push production main
Verify that the website is automatically updated after the push. If it's not, check the post-receive hook permissions and ensure it's executable.
To ensure your website's repository stays in sync on both GitHub and your server, it's important to push changes to both origin
(GitHub) and production
(your server).
Run the following command to push the changes to your GitHub repository:
git push origin main
To update the live website, push the changes to your server's production
remote:
git push production main
Once the changes are pushed to both GitHub and the server, verify the updates:
By pushing to both origin
and production
, you ensure that your codebase is properly backed up on GitHub
If you encounter issues connecting to the remote repository, ensure that the remote URL is correctly configured:
git remote set-url production ssh://@:/var/repo/website.git
After correcting the URL, try pushing again.
If files on the server are not being updated, ensure that all files in the web directory have the correct ownership. The web server user (likely www-data
for Nginx) should own all files:
sudo chown -R www-data:www-data /var/www/html
This ensures the server has permission to serve the updated files.