| |

How to Migrate a Magento 2 Store to a New Host: Complete Step-by-Step Runbook

Migration workflow diagram showing how to migrate Magento 2 store from old host to new host server

Verified Answer

To migrate a Magento 2 store without losing orders, provision a matching PHP, MySQL/MariaDB, Redis, and OpenSearch stack, transfer files and pub/media/ via rsync, import a consistent mysqldump –single-transaction –quick snapshot, update app/etc/env.php, test checkout via hosts override, and run a final delta sync before DNS cutover.

Planning to migrate Magento 2 to a new host without losing orders requires matching stack versions, consistent InnoDB snapshots, and clean credential updates. Follow this end-to-end runbook from rsync and mysqldump to hosts-file verification.

Main Problem

Ad-hoc FTP uploads and unverified SQL dumps corrupt InnoDB foreign keys, drop recent customer orders, and leave OpenSearch indices unbuilt after launch.

Technical Consideration

Using rsync delta transfers and mysqldump --single-transaction --quick lets you pre-stage 99% of data while the live store stays online.

Practical Implication

Testing the fully reindexed target server via your local hosts file catches PHP extension or SSL mismatches before a single shopper sees the new IP.

The High-Stakes Migration: Transferring Production Stores Without Revenue Loss

Migrating a live Magento 2 store is fundamentally a synchronization problem. If your catalog contains 50 GB of product imagery and a 12 GB MySQL database, copying everything over the network takes time—often 30 to 90 minutes depending on disk IOPS and inter-datacenter bandwidth. If you leave the storefront open during a single-pass copy, customers will continue placing orders on the old server after your database dump started, creating missing order records on the new server. Conversely, if you put the store into maintenance mode for the entire 90-minute transfer, you forfeit revenue and frustrate active shoppers.

The solution is a two-stage migration: first perform an initial full synchronization of files and database while the old store remains live, validate every service on the new server, and then execute a fast final delta sync during a brief maintenance window. When combined with a structured zero-downtime DNS cutover protocol, your store transitions cleanly with zero lost transactions.

Phase 1: Pre-Migration Audit of Catalog Storage, Database & Versions

Before copying a single byte, audit your source server to ensure your destination node meets or exceeds every version requirement outlined in our Magento 2 system requirements guide. Recording exact software versions prevents subtle serialization or PHP deprecation crashes after transfer.

Terminal / CLI
# Check Magento version, PHP version, and installed extensions
cd /var/www/magento2
php bin/magento --version
php -v
php -m

# Measure disk usage of media and codebase
du -sh . pub/media var/

# Check MySQL/MariaDB version and total database size
mysql -e "SELECT VERSION();"
mysql -e "SELECT table_schema AS 'DB', ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)' FROM information_schema.TABLES GROUP BY table_schema;"

Also verify whether your store uses an older Elasticsearch 7.x cluster or OpenSearch 2.x, and check crontab -u magento_user -l for custom ERP inventory syncs or third-party feed exporters that must be recreated on the target server.

Phase 2: Provisioning the Target Server Stack

On your new host, provision the complete runtime stack before transferring files: Nginx (configured with document root pointed strictly to /pub), PHP-FPM matching your Magento version (PHP 8.2 or 8.3 for Magento 2.4.7+), MySQL 8.0 or MariaDB 10.6/10.11 LTS, OpenSearch 2.x, Redis (separate instances or databases for cache and sessions), and Varnish if used in production. Create your dedicated CLI user and shared group following the Magento 2 two-user permissions model so transferred files land with clean ownership.

Create an empty target database and a dedicated MySQL user with full privileges on that schema. Avoid reusing root for application database connections.

Phase 3: High-Speed File Transfer via rsync

Never compress 100,000 product images into a massive .tar.gz archive if you have SSH access between servers. Archiving consumes double the disk space on the source server and cannot resume cleanly if a network blip interrupts the transfer. Instead, use rsync over SSH. rsync streams files directly, preserves symlinks and timestamps, compresses payloads in transit with -z, and lets you exclude ephemeral cache and generated directories that should be rebuilt cleanly on the new host.

Terminal / CLI
# Run from the NEW target server, pulling from the OLD source server
rsync -avzP -e "ssh -p 22" \
  --exclude 'var/cache/*' \
  --exclude 'var/page_cache/*' \
  --exclude 'var/session/*' \
  --exclude 'var/view_preprocessed/*' \
  --exclude 'generated/code/*' \
  --exclude 'generated/metadata/*' \
  --exclude 'pub/static/frontend/*' \
  --exclude 'pub/static/adminhtml/*' \
  magento_user@OLD_SERVER_IP:/var/www/magento2/ /var/www/magento2/

Excluding var/cache/, generated/, and compiled pub/static/ folders typically cuts transfer volume by 20% to 40% while preventing stale PHP bytecode or old server paths from polluting the new environment. Note that pub/media/ is included in full so every product photo and CMS banner arrives intact.

Phase 4: Database Export and Import Preserving Foreign Keys

Magento 2 relies heavily on InnoDB foreign key constraints and inventory triggers (such as inventory_source_item and catalog flat/MSI tables). Exporting a live database without --single-transaction locks tables and stalls active customer checkouts; importing a dump that contains hardcoded DEFINER=`old_user`@`localhost` triggers fails immediately if the new host uses a different MySQL username.

Terminal / CLI
# 1. On OLD server: non-blocking InnoDB export with triggers and routines
mysqldump --single-transaction --quick --routines --triggers \
  -u old_db_user -p old_magento_db \
  | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/g' \
  | gzip > /tmp/magento_prestage.sql.gz

# 2. Transfer compressed dump to NEW server
scp /tmp/magento_prestage.sql.gz magento_user@NEW_SERVER_IP:/tmp/

# 3. On NEW server: import while preserving foreign key integrity
gunzip < /tmp/magento_prestage.sql.gz | mysql -u new_db_user -p new_magento_db

The sed filter strips DEFINER clauses from triggers and views so MySQL automatically executes them under the importing user’s context, preventing Access denied; you need the SUPER or SET_USER_ID privilege errors. Because mysqldump writes SET FOREIGN_KEY_CHECKS=0 at the top of the dump and restores SET FOREIGN_KEY_CHECKS=1 at the bottom, table creation order never fails and full foreign key enforcement is active the moment the import finishes.

Phase 5: Re-Mapping Credentials in app/etc/env.php and Reindexing

Once the files and database are staged on the new server, update app/etc/env.php to point to the new MySQL database name, username, password, Redis cache/session sockets or ports, and OpenSearch host. Do not alter the crypt.key value inside env.php—Magento requires the original encryption key to decrypt saved payment gateway API keys, shipping credentials, and customer password hashes.

Terminal / CLI
cd /var/www/magento2

# Recompile DI, deploy static assets, and rebuild OpenSearch indices
sudo -u magento_user php -d memory_limit=4G bin/magento setup:upgrade --keep-generated
sudo -u magento_user php -d memory_limit=4G bin/magento setup:di:compile
sudo -u magento_user php -d memory_limit=4G bin/magento setup:static-content:deploy -f
sudo -u magento_user php bin/magento indexer:reindex
sudo -u magento_user php bin/magento cache:flush

Running bin/magento indexer:reindex now populates the new OpenSearch cluster with your full product catalog so category pages and search bars return instant results during testing.

Phase 6: Testing on the Target Server via Local Hosts File

Never change public DNS until you have verified the new server end-to-end under your real production domain name. Edit your workstation’s local hosts file (C:\Windows\System32\drivers\etc\hosts on Windows or /etc/hosts on macOS/Linux) and map your domain to the new server’s IP address:

Terminal / CLI
NEW_SERVER_IP  yourdomain.com www.yourdomain.com
  • SSL Certificate Validation: Confirm Nginx serves a valid TLS certificate for your domain without mixed-content warnings.
  • Category, Search & Cart Flows: Browse layered navigation, search for SKUs via OpenSearch, add items to the cart, and verify Redis session persistence.
  • Admin Panel & Cron Health: Log into the Magento Admin, upload a test image, and check cron_schedule to confirm background jobs are running.
Terminal / CLI
# Verify HTTP/HTTPS response, Varnish hit headers, and TLS directly against NEW_SERVER_IP
curl -sI --resolve yourdomain.com:443:NEW_SERVER_IP https://yourdomain.com/ | grep -iE "HTTP/|X-Magento-Cache-Debug|strict-transport"

# Confirm OpenSearch cluster health and Redis connectivity on the new host
curl -s http://127.0.0.1:9200/_cluster/health?pretty
redis-cli ping

Phase 7: Final Delta Synchronization and Go-Live Cutover

Once your hosts-file validation passes, schedule a low-traffic cutover window. Enable maintenance mode on the old server (bin/magento maintenance:enable) so no new orders enter the old database. Re-run the exact same rsync command for pub/media/ (which finishes in seconds since only newly uploaded images are copied), take one final mysqldump from the frozen old server, and import it into the new database. Clear Redis and Varnish caches, verify bin/magento maintenance:status is disabled on the new host, and update your DNS A records to the new server IP.

Immediately after lifting maintenance mode on the new server, monitor var/log/exception.log, var/log/system.log, and Nginx error logs for 30 minutes, and confirm that SELECT job_code, status, executed_at FROM cron_schedule ORDER BY executed_at DESC LIMIT 10; shows healthy success executions. Keep the old server powered on (with maintenance mode or a reverse proxy active) for at least 48 hours so you have an instant, intact fallback archive until global DNS propagation is 100% complete.

Frequently Asked Questions

How long does it take to migrate a Magento 2 store to a new host?

Pre-staging files and the initial database typically takes 30 to 90 minutes depending on media size, while the live storefront stays online. Using a two-pass delta sync, actual cutover downtime is usually limited to 5 to 15 minutes.

Should I copy var/cache and generated/ directories to the new server?

No. Exclude var/cache/, var/page_cache/, var/session/, and generated/ during rsync, then regenerate compiled DI classes and static assets cleanly on the target host with bin/magento setup:di:compile and setup:static-content:deploy.

Why do I need to keep the same crypt.key in app/etc/env.php?

Magento uses the crypt.key value in app/etc/env.php to encrypt and decrypt sensitive database values, including payment gateway secret keys and shipping API credentials. Changing it breaks those integrations on the new server.

How do I fix MySQL DEFINER errors when importing a Magento 2 database?

Strip DEFINER clauses from triggers and views during export using sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/g' before importing into the new server’s database.

Can I test my migrated Magento 2 store before changing DNS?

Yes. Add an entry mapping your domain name to the new server’s IP address in your local workstation’s hosts file. Your browser will load the new server under the live domain while public shoppers continue hitting the old host.

How do I verify the new server via CLI without editing my local hosts file?

Use curl -Ik --resolve yourdomain.com:443:NEW_SERVER_IP https://yourdomain.com/. This forces cURL to connect directly to the new server IP while sending the real SNI hostname and Host header for SSL and Nginx virtual host validation.

What if my Magento store uses RabbitMQ message queues during migration?

Wait for RabbitMQ queues on the old server to drain to zero (rabbitmqctl list_queues) after enabling maintenance mode, then recreate the RabbitMQ virtual host and user on the new server and run bin/magento setup:upgrade --keep-generated so Magento declares all exchanges before starting systemd consumers.

Migrate Your Magento Store onto Faster NVMe Stack Without Lost Orders

Moving databases via mysqldump –single-transaction, syncing pub/media/ with rsync, and verifying checkout via hosts overrides keeps migrations predictable. Upgrade your store onto modern PHP 8.3, OpenSearch 2.x, and NVMe infrastructure.

Plan your Magento store migration to Onlive Server