Back to tutorials
Tutorial

Create a Staging Copy of WordPress on the Same VPS

Create a WordPress staging site on the same VPS: clone files + DB, rewrite URLs, block indexing, add basic auth, and verify safely.

By Anurag Singh
Updated on Nov 24, 2026
Category: Tutorial
Share article
Create a Staging Copy of WordPress on the Same VPS

Breaking production during a plugin test is avoidable. This walkthrough shows how to create a WordPress staging site on the same VPS.

You’ll use a separate database, a copied wp-content, URL rewrites, search engine blocking, and HTTP Basic Auth. You’ll end with a staging URL you can test safely—no second server required.

The commands assume a standard Nginx + PHP-FPM + MariaDB/MySQL stack on Ubuntu/Debian/AlmaLinux/Rocky. If you host multiple WordPress installs, repeat the same pattern for each site.

What you’ll build (and what you won’t)

  • Staging site: https://staging.example.com served from a separate document root.
  • Separate database: wordpress_staging with its own DB user.
  • Safe by default: search engines discouraged, Basic Auth enabled, and outbound email optionally disabled.
  • No second server: everything runs on the same VPS, so CPU/RAM/disk planning matters.

If you need hard isolation, put staging on a separate VM. The same applies if you’re already tight on CPU, RAM, or disk.

A HostMyCode VPS makes it easy to add a low-cost staging box later. For now, this guide keeps everything on one server.

Prerequisites and assumptions

Before you touch anything, confirm you have:

  • A working WordPress site at https://example.com.
  • Shell access (SSH) with sudo privileges.
  • Nginx or Apache configured for the production site.
  • Database access credentials for production (wp-config.php).
  • A DNS record ready for staging.example.com pointing to your VPS IP.

Recommended server sizing: most sites can run staging on the same host with 2 vCPU and 2–4 GB RAM. This assumes reasonable caching.

WooCommerce stores with large catalogs can hit the ceiling faster. Imports and re-indexing are common trouble spots.

Quick disk check (staging fails more often on disk than CPU):

df -h
sudo du -sh /var/www/* 2>/dev/null | sort -h

If you’re low on space, fix that first. HostMyCode also has a practical triage guide: Disk Full on VPS: Find Large Files and Free Space Safely.

Step 1: Add DNS for staging

Create an A (or AAAA) record:

  • staging.example.com → your VPS public IP

Verify propagation from your laptop:

dig +short staging.example.com A
# or
nslookup staging.example.com

If you want a clean checklist for DNS changes (and how to avoid accidental downtime), see: Cloudflare DNS setup guide tutorial (2026).

Step 2: Create a new document root and copy WordPress files

In this example, production lives at /var/www/example.com/public. Update paths to match your layout.

# define paths
PROD_ROOT="/var/www/example.com/public"
STAGE_ROOT="/var/www/staging.example.com/public"

# create staging directories
sudo mkdir -p "${STAGE_ROOT}"
sudo mkdir -p /var/www/staging.example.com/logs

# copy files (preserve permissions, symlinks)
sudo rsync -aHAX --delete \
  --exclude 'wp-content/cache/' \
  --exclude 'wp-content/uploads/cache/' \
  "${PROD_ROOT}/" "${STAGE_ROOT}/"

Why exclude cache directories? It prevents stale cache files from coming along. It also reduces copy time.

If a plugin stores real data under wp-content/cache, remove that exclude and copy it.

Set ownership (common Nginx/PHP-FPM user is www-data on Ubuntu/Debian; AlmaLinux/Rocky often uses nginx or apache):

# Ubuntu/Debian
sudo chown -R www-data:www-data /var/www/staging.example.com

# AlmaLinux/Rocky (pick the right one for your stack)
# sudo chown -R nginx:nginx /var/www/staging.example.com
# sudo chown -R apache:apache /var/www/staging.example.com

Verify:

ls -la /var/www/staging.example.com/public | head

Step 3: Clone the database to a new staging database

Most staging breakage starts here. Common causes are the wrong character set, wrong credentials, or a shared DB user.

Take the extra minute and do a clean clone.

3.1 Find production DB credentials

On the server, open the production config:

sudo sed -n '1,120p' /var/www/example.com/public/wp-config.php

Record these values:

  • DB_NAME
  • DB_USER
  • DB_PASSWORD
  • DB_HOST (often localhost)

3.2 Create staging DB + user

Log into MariaDB/MySQL:

sudo mysql

Create a new database and user (change passwords):

CREATE DATABASE wordpress_staging DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE USER 'wpstage'@'localhost' IDENTIFIED BY 'use-a-long-random-password-here';
GRANT ALL PRIVILEGES ON wordpress_staging.* TO 'wpstage'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Common mistake: reusing the production DB user. Don’t.

One typo in staging should never be able to drop production tables.

3.3 Dump production and import into staging

Use mysqldump with sensible flags. Replace PROD_DB and PROD_USER as needed.

PROD_DB="wordpress_prod"
PROD_USER="wpuser"

# create a dump (you will be prompted for password)
mysqldump --single-transaction --routines --triggers \
  --default-character-set=utf8mb4 \
  -u "${PROD_USER}" -p "${PROD_DB}" \
  | mysql -u wpstage -p wordpress_staging

Verify the import:

mysql -u wpstage -p -e "SHOW TABLES;" wordpress_staging | head
mysql -u wpstage -p -e "SELECT COUNT(*) AS posts FROM wp_posts;" wordpress_staging

If you want a tighter backup routine (with restore tests), HostMyCode has a tutorial that pairs well with staging work: Set Up Automatic MySQL Backups With Tested Restores.

Step 4: Point staging wp-config.php at the staging database

Edit the staging wp-config.php. Replace the DB settings to match wordpress_staging and wpstage.

sudo cp "${STAGE_ROOT}/wp-config.php" "${STAGE_ROOT}/wp-config.php.bak"
sudo nano "${STAGE_ROOT}/wp-config.php"

Update these lines:

define('DB_NAME', 'wordpress_staging');
define('DB_USER', 'wpstage');
define('DB_PASSWORD', 'use-a-long-random-password-here');
define('DB_HOST', 'localhost');

Optional but recommended: add a visible environment label for admins. Put this near the top (after <?php):

define('WP_ENVIRONMENT_TYPE', 'staging');

Step 5: Rewrite site URLs inside the staging database

This step makes staging behave like staging. If you skip it, you’ll often get redirects back to production.

You can also see mixed content or login/session issues.

WP-CLI is the safest way to do this. Install it if needed:

sudo -u www-data bash -c 'command -v wp || true'

# If missing (Ubuntu/Debian example)
curl -sS -o wp-cli.phar https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
php wp-cli.phar --info
sudo chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

First, confirm WP-CLI can read the staging install:

sudo -u www-data wp --path="${STAGE_ROOT}" core version

Update the key options, then run a dry-run search-replace:

STAGE_URL="https://staging.example.com"
PROD_URL="https://example.com"

sudo -u www-data wp --path="${STAGE_ROOT}" option update home "${STAGE_URL}"
sudo -u www-data wp --path="${STAGE_ROOT}" option update siteurl "${STAGE_URL}"

# dry run first
sudo -u www-data wp --path="${STAGE_ROOT}" search-replace "${PROD_URL}" "${STAGE_URL}" --dry-run --all-tables

If the dry-run output looks reasonable, run the real replacement:

sudo -u www-data wp --path="${STAGE_ROOT}" search-replace "${PROD_URL}" "${STAGE_URL}" --all-tables

Verify:

sudo -u www-data wp --path="${STAGE_ROOT}" option get home
sudo -u www-data wp --path="${STAGE_ROOT}" option get siteurl

Common mistake: doing a raw SQL replace and corrupting serialized data.

WP-CLI handles serialization correctly.

Step 6: Add an Nginx (or Apache) vhost for staging

Use the example that matches your stack. If you already use a shared include for WordPress settings, reuse it here.

Nginx example (Ubuntu/Debian typical paths)

Create a new server block:

sudo nano /etc/nginx/sites-available/staging.example.com
server {
    listen 80;
    server_name staging.example.com;

    root /var/www/staging.example.com/public;
    index index.php index.html;

    access_log /var/www/staging.example.com/logs/access.log;
    error_log  /var/www/staging.example.com/logs/error.log;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2?)$ {
        expires 7d;
        access_log off;
    }
}

Enable it and test:

sudo ln -s /etc/nginx/sites-available/staging.example.com /etc/nginx/sites-enabled/staging.example.com
sudo nginx -t
sudo systemctl reload nginx

If your PHP-FPM socket differs, list available sockets:

ls -l /run/php/

Apache example (CentOS Stream/AlmaLinux/Rocky common pattern)

Create:

sudo nano /etc/httpd/conf.d/staging.example.com.conf
<VirtualHost *:80>
  ServerName staging.example.com
  DocumentRoot /var/www/staging.example.com/public

  ErrorLog  /var/www/staging.example.com/logs/error.log
  CustomLog /var/www/staging.example.com/logs/access.log combined

  <Directory /var/www/staging.example.com/public>
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

Reload Apache:

sudo apachectl configtest
sudo systemctl reload httpd

Step 7: Add TLS for staging (Let’s Encrypt)

Use Certbot. Package names vary slightly by distro, but the flow is the same.

Nginx + Certbot (Ubuntu/Debian)

sudo apt update
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d staging.example.com

Apache + Certbot (AlmaLinux/Rocky)

sudo dnf install -y certbot python3-certbot-apache
sudo certbot --apache -d staging.example.com

Verify auto-renew:

sudo certbot renew --dry-run

If you want modern transport settings, you can optionally enable HTTP/3 on supported Nginx builds. Reference: Enable HTTP/3 on Nginx With QUIC on Ubuntu VPS.

Step 8: Lock staging behind HTTP Basic Auth

“Discourage indexing” helps, but it doesn’t keep people out. If someone guesses the URL, they can still reach /wp-admin.

Basic Auth blocks casual access and cuts bot traffic.

8.1 Create credentials

Install apache2-utils (Debian/Ubuntu) or httpd-tools (RHEL family) to get htpasswd:

# Ubuntu/Debian
sudo apt install -y apache2-utils

# AlmaLinux/Rocky
# sudo dnf install -y httpd-tools

Create an htpasswd file:

sudo mkdir -p /etc/nginx/auth
sudo htpasswd -c /etc/nginx/auth/staging.htpasswd stageadmin

8.2 Enable Basic Auth in your vhost

For Nginx, edit /etc/nginx/sites-available/staging.example.com. Add this inside the server { } block:

auth_basic "Staging";
auth_basic_user_file /etc/nginx/auth/staging.htpasswd;

Reload Nginx:

sudo nginx -t
sudo systemctl reload nginx

Verify: open https://staging.example.com in an incognito window. You should see a password prompt before WordPress loads.

Step 9: Discourage indexing and stop accidental email sends

Two mistakes show up constantly: staging gets indexed, or staging emails real users.

Treat both as mandatory fixes.

9.1 Block indexing at multiple layers

WordPress layer: set “Discourage search engines”:

sudo -u www-data wp --path="${STAGE_ROOT}" option update blog_public 0

HTTP layer (recommended): add an X-Robots-Tag header in your staging vhost:

add_header X-Robots-Tag "noindex, nofollow, nosnippet, noarchive" always;

Verify headers:

curl -I https://staging.example.com | grep -i robots

9.2 Disable outbound emails from staging

The simplest path is a plugin like “WP Mail Logging” plus disabling actual sends.

If you want a hard stop, block mail in code. Add this to wp-config.php on staging only:

define('WP_MAIL_DISABLED', true);

Then create wp-content/mu-plugins/disable-mail.php:

sudo -u www-data mkdir -p "${STAGE_ROOT}/wp-content/mu-plugins"
sudo -u www-data nano "${STAGE_ROOT}/wp-content/mu-plugins/disable-mail.php"
<?php
/*
Plugin Name: Disable Mail (Staging)
*/

if (defined('WP_MAIL_DISABLED') && WP_MAIL_DISABLED) {
  add_filter('wp_mail', function($args) {
    $args['to'] = 'devnull@example.invalid';
    $args['subject'] = '[STAGING BLOCKED] ' . $args['subject'];
    $args['message'] = "Blocked email on staging.\n\n" . $args['message'];
    return $args;
  });

  add_filter('pre_wp_mail', function($return, $atts) {
    return true; // short-circuit send
  }, 10, 2);
}

Verify: trigger a password reset email in staging. It should not arrive.

Step 10: Prevent staging from touching production integrations

Staging should never hit live payment gateways, CRMs, or production API keys. You won’t catch every plugin automatically.

You can still cut the biggest risks quickly:

  • WooCommerce: enable test mode for payment gateways; set a fake “From” address.
  • CDN/WAF: don’t point staging at the same “origin pull” rules if they’re strict.
  • Webhooks: disable outgoing webhooks or route them to a request bin.

A useful pattern is to define staging-only constants in wp-config.php. Then have your custom code (or MU plugins) key off them:

define('HMC_STAGING', true);

Step 11: Performance and safety tweaks for same-server staging

On a single VPS, staging and production share the same CPU and RAM.

Keep staging “quiet” so a test run doesn’t become a production incident.

  • Cron: don’t let two sites run heavy WP-Cron at the same time.
  • Caching: disable full-page cache plugins on staging if they make debugging harder.
  • Object cache: if you use Redis, don’t share the same prefix/database number with production.

If you use Redis object caching, separate the keyspace. Most Redis plugins support a prefix.

For Redis setup details, see: Set Up Redis for WordPress With Nginx and PHP-FPM.

Optional: isolate PHP-FPM pools

If production is sensitive to load spikes, give staging its own PHP-FPM pool. Set limits so staging can’t starve production.

On Ubuntu with PHP 8.3:

sudo cp /etc/php/8.3/fpm/pool.d/www.conf /etc/php/8.3/fpm/pool.d/staging.conf
sudo nano /etc/php/8.3/fpm/pool.d/staging.conf

Edit values:

[staging]
user = www-data
group = www-data
listen = /run/php/php8.3-fpm-staging.sock

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Then update staging Nginx vhost:

fastcgi_pass unix:/run/php/php8.3-fpm-staging.sock;

Restart and verify:

sudo systemctl restart php8.3-fpm
sudo nginx -t
sudo systemctl reload nginx
ss -lpn | grep php8.3-fpm-staging

Step 12: Validate the staging copy end-to-end

Don’t stop at “the homepage loads.” Do a quick pass across the basics.

  • Login: you can log into /wp-admin and the URL stays on staging.
  • Permalinks: a few posts load and don’t redirect to production.
  • Uploads: images load from the staging domain.
  • Robots: X-Robots-Tag shows noindex.
  • Email: password reset doesn’t send real mail.
  • Database separation: staging changes don’t appear in production.

Confirm database separation by adding a temporary post in staging, then checking production:

# staging: create a quick draft
sudo -u www-data wp --path="${STAGE_ROOT}" post create --post_title="STAGING TEST" --post_status=draft

# production should not contain it
sudo -u www-data wp --path="${PROD_ROOT}" post list --search="STAGING TEST"

Common mistakes (and fast fixes)

  • Staging redirects to production: re-check home and siteurl; then re-run WP-CLI search-replace.
  • Mixed content warnings: confirm staging TLS is active, then search-replace http://example.com to https://staging.example.com too.
  • Media loads from production: your theme/plugin may be hardcoding URLs; search the codebase: grep -R "example.com" -n wp-content.
  • 403/502 errors: wrong permissions or wrong PHP-FPM socket; check error.log and journalctl -u php8.3-fpm -n 50.
  • Staging indexed by Google: Basic Auth should stop most crawlers; also keep X-Robots-Tag and blog_public=0.

Operational tip: keep staging fresh (without repeating the whole process)

Once staging exists, a refresh is usually three moves. Re-rsync files, re-import the DB, then re-run search-replace.

You can script this later. Do it manually a few times first. That way, you know exactly what the script will change.

At minimum, keep a short runbook in your repo or password manager with:

  • Production root and staging root paths
  • Production DB name and staging DB name
  • WP-CLI commands you used
  • Nginx/Apache vhost path

If you want staging without fighting noisy neighbors, slow disks, or unpredictable I/O, run it on infrastructure sized for steady workloads. A HostMyCode VPS gives you consistent resources, and managed VPS hosting can handle patching, web stack tuning, and routine checks while you focus on the site.

FAQ

Will staging slow down my production WordPress site?

It can if you run heavy imports, search indexing, or image regeneration on staging. Keep staging behind Basic Auth, cap PHP-FPM for staging, and avoid running both sites’ cron-heavy tasks at the same time.

Do I need a separate database user for staging?

Yes. Separate user + separate database is the safety line that prevents a staging mistake from damaging production.

How do I stop staging from sending real emails?

The most reliable approach is to block sends in code (MU plugin) and/or route SMTP to a sink. This tutorial includes a simple MU plugin that short-circuits wp_mail.

Can I create staging under a subfolder like /staging instead of a subdomain?

You can, but it’s messier: cookie paths, caching, and redirects become harder. A subdomain is simpler to secure and easier to remove later.

Should I block staging by IP instead of Basic Auth?

IP allowlisting is strong if your team has stable IPs or a VPN. Basic Auth is a good default because it works even when you’re traveling or on dynamic networks.

Summary: your safe same-server staging workflow

You now have a staging copy running on the same VPS without sharing production data. You have a separate document root, a separate database, and safely rewritten URLs.

Indexing is discouraged, and Basic Auth guards the front door. If you decide later to create a WordPress staging site on its own VM, you can reuse the same steps—then repoint DNS.

For predictable performance and room to grow, start with a HostMyCode VPS and move to managed service when you’d rather ship changes than maintain servers.