Deploying WordPress updates manually can be slow and cause errors, especially when managing multiple environments or frequent changes. In this guide, you’ll learn how to set up automatic WordPress deployment on VPS with Git hooks, which enables a simple and reliable continuous deployment workflow.
We will push code from the local machine to a remote Git repository on the server, then a post-receive hook will automatically check out the latest code into a timestamped release folder and update a symlink (current/) to switch versions instantly, which ensures zero downtime.
Shared files like uploads, configuration, and environment variables stay persistent across deployments.
By the end of this article, you will have a clean structure for managing staging and production environments from the same repository, which all run on an Ubuntu VPS with Nginx and PHP-FPM.
If you’re looking for a reliable environment to host and scale your WordPress projects, consider our flexible VPS hosting solutions, which offer full SSH access and powerful performance for professional deployment workflows.
Preparation for WordPress Deployment in VPS with Git Hooks
The first step is to prepare your VPS by running the system update, installing the required packages, and tools.
To run the system update and upgrade, use the command below:
Bash
sudoaptupdate&&sudoaptupgrade-y
Install Nginx and essential tools with the following command:
Bash
sudoaptinstallnginxgitunzipcurl-y
Install PHP and its required extensions for WordPress with the following command:
You must create a user database for WordPress and grant all privileges to it with the following commands:
Bash
sudomysql-e"CREATE DATABASE wpdb DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"sudomysql-e"CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'Strong_DB_Pass_ChangeMe';"sudomysql-e"GRANT ALL PRIVILEGES ON wpdb.* TO 'wpuser'@'localhost'; FLUSH PRIVILEGES;"
Also, you must install WP-CLI, which is a powerful command-line tool for managing WordPress. To set up WP-CLI, you can use the commands below:
Configure Nginx Server Block for WordPress Deployment
This Nginx configuration serves as the public gateway to your application and works seamlessly with the deployment folder structure by pointing the document root to the current symlink, which allows for atomic release switches.
To create the Nginx configuration file for the WordPress deployment, run the command below:
Bash
sudotee/etc/nginx/sites-available/example.com<<'NGINX'server{listen80;server_nameexample.comwww.example.com;root/var/www/example.com/current;# symlink switches atomically per releaseindexindex.phpindex.html;# Serve uploads & static quicklylocation~*\.(jpg|jpeg|gif|png|webp|svg|css|js|ico|woff2?)$ {access_logoff;log_not_foundoff;expires 7d;try_files$uri$uri/=404;}# Deny access to sensitive fileslocation~*\.(env|ini|log|sql|bak|sh)$ {denyall;}# WordPress rewriteslocation/{try_files$uri$uri//index.php?$args;}# PHP-FPMlocation~\.php$ {includesnippets/fastcgi-php.conf;fastcgi_passunix:/run/php/php8.2-fpm.sock;# adjust version if neededfastcgi_paramSCRIPT_FILENAME$document_root$fastcgi_script_name;includefastcgi_params;}}NGINX
Enable the Nginx server block, check for syntax errors, and restart Nginx with the following commands:
Note for Apache users: The principle is the same; you must set your DocumentRoot to /var/www/example.com/current. The rest of your deployment structure and logic remains unchanged.
Automate WordPress Deployment with a Git Hook
In this step, you can automate the entire deployment process, which transforms a simple git push into a powerful and production-ready release.
Create a bare Git repository on the server that acts as a receiver for your code with the commands below:
Next, create the post-receive hook script, which is configured to automatically deploy every push to the main branch. The following script handles creating timestamped releases, symlinking shared files, updating permissions, and cleanly switching the live site:
Bash
sudo-udeploytee/var/repo/wp-site.git/hooks/post-receive<<'HOOK'#!/usr/bin/env bashset-euopipefail# CONFIGAPP_NAME="wp-site"REPO_DIR="/var/repo/wp-site.git"BASE="/var/www/example.com"RELEASES="$BASE/releases"CURRENT="$BASE/current"SHARED="$BASE/shared"KEEP_RELEASES=5# Branch mapping: deploy only from specific branches# You can add staging mapping if neededreadoldrevnewrevrefnamebranch="${refname##refs/heads/}"if[["$branch"!="main"&&"$branch"!="master"]];thenecho"Skipping deploy (branch '$branch' is not set for deployment)."exit0fitimestamp="$(date +%Y%m%d%H%M%S)"new_release="$RELEASES/$timestamp"echo"==> Creating release: $new_release"mkdir-p"$new_release"echo"==> Checking out code"GIT_WORK_TREE="$new_release"git--git-dir="$REPO_DIR"checkout-f"$branch"# Ensure shared directories existmkdir-p"$SHARED/uploads""$SHARED/env"# Link shared content into releaseecho"==> Linking shared folders/files"rm-rf"$new_release/wp-content/uploads"ln-s"$SHARED/uploads""$new_release/wp-content/uploads"# If using .env or environment files for wp-config.phpif[[-f"$SHARED/env/.env"]];thenln-sf"$SHARED/env/.env""$new_release/.env"fi# Permissionsecho"==> Setting permissions"chown-Rdeploy:www-data"$new_release"find"$new_release"-typed-execchmod2775{}\;find"$new_release"-typef-execchmod664{}\;# Optional: Composer install if presentif[[-f"$new_release/composer.json"]];thenecho"==> Running composer install (no-dev, optimized)"ifcommand-vcomposer>/dev/null2>&1;then(cd"$new_release"&&composerinstall--no-dev--prefer-dist--no-interaction--optimize-autoloader)elseecho"composer not found; skipping"fifi# Optional: build assets if you keep a build step (npm, etc.)# (cd "$new_release" && npm ci && npm run build) || true# Maintenance mode (optional; typically not needed for fast swaps)# /usr/local/bin/wp --path="$new_release" maintenance-mode activate || trueecho"==> Activating new release"ln-sfn"$new_release""$CURRENT"# Reload PHP-FPM to clear OPcache (fast & safe)echo"==> Reloading PHP-FPM"sudo/bin/systemctlreloadphp8.2-fpm||true# /usr/local/bin/wp --path="$CURRENT" maintenance-mode deactivate || true# Clean up old releasesecho"==> Cleaning old releases"cd"$RELEASES"ls-1dt*/|tail-n+$((KEEP_RELEASES+1))|xargs-rrm-rfecho"==> Deploy complete for branch '$branch' → $new_release"HOOK
Finally, make the deployment script executable, so it can run automatically when you push code to the server:
A clean Git repository is essential for smooth deployments. This involves adding your custom code, such as themes and plugins, while excluding sensitive directories like uploads and cache.
Here is a .gitignore example in your project root:
Note: If you use Composer to manage WordPress and plugins, keep composer.lock in the repository and let the hook run composer install.
Perform First WordPress Deployment with Git Push
At this point, you must initialize your local Git repository, link it to the server, and push your code. The post-receive hook on the server will create the first release and atomically switch the current symlink, which makes your site live.
To create the repository, you can use the command below or use your existing project folder:
Deploy Future Changes: For all subsequent updates, this single command is all you need. The entire deployment process is now automated.
Final WordPress Configuration Setup
After your first successful deployment, you need to complete the WordPress setup. For a fresh site, use the following WP-CLI commands to generate the wp-config.php file and install WordPress core:
Note: If you are migrating an existing site, you can skip the core installation.
Bash
cd/var/www/example.com/current# Create wp-config if you keep an example in repo; otherwise use WP-CLIwpconfigcreate\--dbname=wpdb--dbuser=wpuser--dbpass='Strong_DB_Pass_ChangeMe'--dbhost=localhost\--dbprefix=wp_--skip-check# Install corewpcoreinstall\--url="https://example.com"\--title="PerLod Production"\--admin_user="admin"\--admin_password="ChangeThisAdminPass!"\--admin_email="admin@example.com"# Set file permissions (once more, just to be sure)sudochown-Rdeploy:www-data/var/www/example.comsudofind/var/www/example.com-typed-execchmod2775{}\;sudofind/var/www/example.com-typef-execchmod664{}\;
Set Up a Staging Environment from the Same Repository (Optional)
You can extend this deployment system to support a separate staging environment from the same repository. By modifying the post-receive hook to deploy different branches to different server paths, you can push to staging for testing and main for production:
Bash
# in post-receive, replace the mapping with:if[["$branch"=="main"]];thenBASE="/var/www/example.com"elif[["$branch"=="staging"]];thenBASE="/var/www/staging.example.com"elseecho"Skipping deploy for branch '$branch'"exit0fi# The rest of the script stays the same, using $BASE
Just as you did for production, create a new Nginx virtual host for staging.example.com that uses the staging site's current symlink as its document root.
Instant WordPress Deployment Rollback to a Previous Version
To quickly rollback a problematic deployment, you can manually point the current symlink to an older release directory and reload the web services. In this way, your shared uploads and environment files remain unaffected.
To ensure WordPress can function properly, you must set the correct ownership and permissions that allow file uploads via the admin while keeping code secure.
To ensure the deploy user owns the code, run the command below:
Bash
sudochown-Rdeploy:www-data/var/www/example.com
Also, you can use ACLs alternative method for this:
Instead of writing your database details directly in the wp-config.php file, you can use an environment variable that loads them from a .env file that’s stored safely outside the web folder. This will keep your sensitive information secure and make it easy to use different settings for staging and production.
This wp-config.php file lives in your Git repository and gets deployed with every release:
PHP
1<?php2// Load .env if present3if(file_exists(__DIR__ .'/.env')){4 $env =parse_ini_file(__DIR__ .'/.env');5foreach($env as $k => $v) $_ENV[$k]= $v;6}78define('DB_NAME', $_ENV['DB_NAME']??'wpdb');9define('DB_USER', $_ENV['DB_USER']??'wpuser');10define('DB_PASSWORD', $_ENV['DB_PASS']??'Strong_DB_Pass_ChangeMe');11define('DB_HOST', $_ENV['DB_HOST']??'localhost');12define('DB_CHARSET','utf8mb4');13define('DB_COLLATE','');1415$table_prefix = $_ENV['DB_PREFIX']??'wp_';1617define('WP_DEBUG',false);1819// Harden file edit in admin20define('DISALLOW_FILE_EDIT',true);2122// Standard WordPress bootstrap23if(!defined('ABSPATH'))define('ABSPATH', __DIR__ .'/');24require_once ABSPATH .'wp-settings.php';
Here is an example Env file in /var/www/example.com/shared/env/.env:
Setting up WordPress Deployment in VPS with Git Hooks makes your workflow faster, safer, and more modern. With this system, every time you push changes to your Git repository, your site updates automatically with no manual uploads or version mix-ups.
Whether you’re using PerLod Hosting or any VPS with root access, this step-by-step guide helps you implement a professional deployment workflow.
We hope you enjoy this guide. Subscribe to our X and Facebook channels to get the latest WordPress and hosting articles.
Git hooks are scripts that run automatically when certain Git events occur. Using a post-receive hook on your VPS lets you automatically deploy code when you push to your remote repository.
No. WordPress core files are version-controlled, and the database remains intact. The deployment only updates files, not your content or settings.
A bare repository doesn’t have a working directory. It only stores Git data and is designed to serve as a remote endpoint for pushes.
Your deployment hook checks out a working copy from this bare repo into your live directory.
We use cookies to run PerLod and to understand how the site is used. You can accept everything, or open Manage to turn individual categories off. Cookie policy.