A distribution company asked us to "rewrite the portal" in 2023. It was a PHP 5.6 application from 2012: 400 files, no framework, SQL in the templates, and a cron folder nobody dared to open. It ran their ordering, invoicing and dealer accounts, and it made money every day. A previous agency had tried a full rewrite. After eleven months they had a beautiful new app that covered about 60% of the features, while the old one kept changing underneath them. The project was cancelled. We took a different route: we put a router in front of the old app and moved one page at a time to a new Laravel application. The first route went live in week three. Fourteen months later the old app served nothing, and we turned it off on a Tuesday afternoon without a maintenance window.
I wrote this with help from AI tools and checked the configuration against the Nginx and Laravel documentation and Martin Fowler's original description of the strangler fig pattern. I am a Principal Software Engineer in Karachi with 9+ years across PHP/Laravel, Vue, Node and .NET microservices, and this is the approach we use at Loop Origin for legacy modernization work.
📚 Series Navigation — Modernizing Legacy PHP Without a Rewrite
- Part 1 (This Post): Strangler Fig for Legacy PHP: Run Old and New Side by Side
- Part 2: Untangling Dependency Cycles in a Modular Laravel Monolith
- Part 3: Upgrading Old PHP Versions Safely With Rector and CI
- Part 4: Replacing Legacy Auth & Sessions Without Logging Everyone Out
- Part 5: From FTP Deploys and Cron Scripts to a Real Pipeline
- Part 6: Decommissioning the Old App: Shadow Traffic, Flags & Final Cutover
Related earlier posts: Characterization Tests Before You Refactor AI-Written Code · Zero-Downtime Database Migrations in Laravel & Node.js SaaS
What is the strangler fig pattern for legacy PHP?
Direct answer: Put a routing layer (usually Nginx) in front of the legacy app, build a new application next to it, and move traffic one route at a time. Both apps share the database and the login session during the transition. The old app shrinks until it serves nothing, then you remove it, with no big-bang cutover.
Why rewrites stall
Every full rewrite I have watched fail failed for the same reasons:
- The target moves. The business keeps asking for changes in the old app, so the new one chases a moving spec.
- No value until the end. Months of work, zero features in production, and stakeholders lose patience.
- Hidden behaviour. Legacy code is full of rules nobody documented: rounding in invoices, a special discount for one dealer, an email that only goes out on Fridays. You find them only when users complain after cutover.
The strangler fig avoids all three. Each migrated route goes live on its own, the old app keeps working for everything else, and hidden behaviour surfaces one page at a time, where it is cheap to fix.
Rewrite vs strangler fig vs refactor in place
| Approach | First value in production | Risk at cutover | Works when | Main cost |
|---|---|---|---|---|
| Big-bang rewrite | Months, often a year | Very high, everything at once | App is small or truly dead | Chasing a moving target |
| Strangler fig | Weeks | Low, one route at a time | App is large and still earning | Running two apps for a while |
| Refactor in place | Days | Low to medium | Codebase is salvageable, framework exists | Slow on very old code with no tests |
For a 2012 framework-less app on PHP 5.6, refactoring in place was not realistic: you cannot install modern packages, and every change risks breaking a page with no tests. The strangler fig let us write new code on PHP 8.3 and Laravel from day one.
Step 1: the routing layer
The router is the heart of the pattern. I use Nginx in front of both apps, with an explicit list of migrated paths. Everything else falls through to the legacy app.
# /etc/nginx/sites-available/portal.conf upstream legacy { server 127.0.0.1:8081; } # PHP 5.6 app (php-fpm via Apache or separate vhost) upstream modern { server 127.0.0.1:8082; } # Laravel on PHP 8.3 map $uri $backend { default legacy; ~^/dealers(/|$) modern; ~^/api/v2/ modern; ~^/invoices/[0-9]+/pdf$ modern; } server { listen 443 ssl http2; server_name portal.example.com; location / { proxy_pass http://$backend; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Request-Id $request_id; add_header X-Served-By $backend always; # remove after cutover } } The map keeps all routing decisions in one readable block that lives in version control. The X-Served-By header is a small trick that saves hours: when someone reports a bug, you know immediately which app served the page.
Step 2: share the session
Users must not log in twice. On that project, the legacy app stored its session in PHP's native files with a PHPSESSID cookie and a $_SESSION['user_id']. We moved the legacy session storage to Redis first (a two-line php.ini change), then gave Laravel a small middleware that reads it:
// app/Http/Middleware/LegacySession.php public function handle(Request $request, Closure $next) { if (! Auth::check() && $sid = $request->cookie('PHPSESSID')) { $raw = Redis::connection('legacy')->get("PHPREDIS_SESSION:{$sid}"); $data = $raw ? LegacySessionDecoder::decode($raw) : []; if (! empty($data['user_id'])) { Auth::onceUsingId((int) $data['user_id']); } } return $next($request); } This is read-only on purpose: the legacy app stays the owner of login until Part 4 of this series, where we move authentication itself. Auth::onceUsingId authenticates for one request without creating a second, competing session.
Step 3: share the database, carefully
Both apps read and write the same MySQL database during the transition. Two rules keep that safe:
- One writer per table at a time. When a feature moves to the new app, its tables move with it. The legacy app may still read them, but it should no longer write them. We track this in the ledger below.
- Schema changes go expand/contract. Add columns and tables first, migrate code, then remove the old structure later, so the legacy app never breaks on a missing column.
New Laravel models map onto old tables with explicit names and no assumptions:
class Dealer extends Model { protected $table = 'tbl_dealers'; protected $primaryKey = 'dealer_id'; public $timestamps = false; // legacy table has created_on only protected $casts = ['created_on' => 'datetime', 'credit_limit' => 'decimal:2']; } Step 4: the migration ledger
The ledger is a simple table in the repository that lists every route, its owner app, the tables it writes, and its status. It turns "how far along are we?" into a number:
| Route | Owner | Writes tables | Tests | Status | |--------------------|---------|------------------------|-------|----------| | /dealers/* | modern | tbl_dealers | 41 | LIVE | | /invoices/:id/pdf | modern | (read-only) | 12 | LIVE | | /orders/new | legacy | tbl_orders, tbl_lines | 0 | NEXT | | /reports/monthly | legacy | (read-only) | 0 | PLANNED | | /cron/sync_stock | legacy | tbl_stock | 0 | PLANNED | We picked the order by value and risk: first the read-only pages that customers complained about (fast, low risk, visible win), then self-contained features like dealer management, and last the order flow that touched the most tables. Before moving each route we wrote characterization tests against the legacy output, so we could prove the new page produced the same numbers.
Picking the first route
The best first route is visible, read-only and annoying. On that project it was the invoice PDF: slow, ugly and generated by a 900-line script. Rebuilding it in Laravel took four days, it shipped behind the router in week three, and the client could see progress immediately. That first win bought us the trust for the next thirteen months.
If your team needs help planning this kind of migration, our Laravel development and custom web application pages describe how we work, and you can get in touch with your stack details.
Diagnostic checklist
- [ ] A router sits in front of both apps with migrated paths listed in version control
- [ ] Every response says which app served it (
X-Served-Byor a log field) - [ ] Users stay logged in across both apps with one session
- [ ] Each table has exactly one writing app at a time
- [ ] Schema changes follow expand/contract so the legacy app never breaks
- [ ] A migration ledger lists every route, owner, tables and status
- [ ] Characterization tests exist before a route moves
- [ ] The first migrated route is visible, read-only and live within weeks
FAQ
Can I do this without Nginx?
Yes. Any reverse proxy works: Apache with mod_proxy, Caddy, a load balancer, or even the new app itself forwarding unknown routes to the old one. Nginx is just the most common in PHP shops.
What about URLs generated inside the legacy app?
Keep URLs stable. The router decides which app serves a path, so old links keep working, and you do not need to change templates in the legacy code.
How long does a strangler migration take?
It depends on size. Our 400-file portal took fourteen months part-time, but it delivered value from week three, which is the point.
Should the new app use a new database?
Not at first. Sharing the database avoids data sync, which is the hardest part of any migration. Split the data later, once the old app is gone.
What if the legacy app runs on a PHP version the server no longer supports?
Run it in its own container or vhost with the old PHP version, isolated from the internet except through the router. Part 3 covers upgrading versions where that is possible.
When can I turn off the old app?
When the ledger shows every route owned by the new app and your logs show no traffic reaching the legacy upstream for a few weeks. Part 6 covers that final cutover.
Next in this series, Part 2 looks at untangling dependency cycles once your new Laravel app starts growing modules.
Follow & Connect
- Website: Loop Origin
- Watch on YouTube: Resume Boost AI · PixelValut · Daily AI News By Ali
- LinkedIn: Loop Origin
- X: Muhammad Ali Mughal (@AliMughal887)
- GitHub: Loop Origin (@LoopOrigin)


