# Deploying the Intelliworkz SEO Platform on a VPS

Target: one Ubuntu 24.04 LTS VPS running Nginx, PHP-FPM 8.4, MySQL 8.4 LTS, Redis 7, Supervisor and cron. All commands assume a sudo user; the app runs as an unprivileged `deploy` user.

Ready-made config files are in `deploy/`.

## 1. Sizing

| Portfolio | VPS | Notes |
|---|---|---|
| Up to ~50 sites, ≤500 pages each, weekly crawls | 2 vCPU / 4 GB RAM / 60 GB SSD | `seo-crawl` numprocs=2, max concurrent crawls 2 |
| 50–150 sites, ≤2,000 pages | 4 vCPU / 8 GB RAM / 120 GB SSD | Recommended starting point. numprocs=3, concurrent crawls 3 |
| 150+ sites or 10k+ page sites | 8 vCPU / 16 GB, MySQL on its own disk | Add crawl workers, lower snapshot retention |

What grows: `crawl_links` and `crawl_pages` (≈ pages × average internal links per crawl, kept for the last *N* crawls per site — Settings → Retention). Settings → Crawling & capacity shows live estimates of crawl requests, uptime checks and API calls per month. The System page shows database size, disk use and queue latency.

Any Indian or UAE region VPS works (DigitalOcean BLR1, AWS ap-south-1 / me-central-1, Hetzner, Linode). Pick the region nearest the client sites so response-time measurements are realistic.

## 2. Server packages

```bash
sudo timedatectl set-timezone Asia/Kolkata
sudo apt update && sudo apt -y upgrade
sudo apt -y install software-properties-common curl git unzip ufw supervisor nginx redis-server mysql-server poppler-utils
sudo add-apt-repository -y ppa:ondrej/php && sudo apt update
sudo apt -y install php8.4-fpm php8.4-cli php8.4-mysql php8.4-redis php8.4-mbstring php8.4-xml php8.4-curl php8.4-gd php8.4-intl php8.4-zip php8.4-bcmath php8.4-opcache
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt -y install nodejs   # build step only
```

Laravel 13 supports PHP 8.3–8.5; the app was built and tested on PHP 8.3 with MariaDB 10.11 and Redis 7. PHP 8.4 + MySQL 8.4 LTS is the recommended production pair.

PHP settings (`/etc/php/8.4/fpm/conf.d/99-seo.ini` and the same for `cli`):

```ini
memory_limit = 512M
upload_max_filesize = 10M
post_max_size = 12M
opcache.enable = 1
opcache.memory_consumption = 192
opcache.validate_timestamps = 0   ; deploy.sh reloads FPM after each release
```

Firewall:

```bash
sudo ufw allow OpenSSH && sudo ufw allow 'Nginx Full' && sudo ufw enable
```

Redis: keep it bound to 127.0.0.1 (default) and set a password in `/etc/redis/redis.conf` (`requirepass …`), then put it in `.env` as `REDIS_PASSWORD`. Set `maxmemory-policy noeviction` so queued jobs are never evicted.

## 3. Database

```bash
sudo mysql_secure_installation
sudo mysql <<'SQL'
CREATE DATABASE seo_platform CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'seo'@'localhost' IDENTIFIED BY 'CHANGE_ME_long_random';
GRANT ALL ON seo_platform.* TO 'seo'@'localhost';
-- read-only user for backups
CREATE USER 'seo_backup'@'localhost' IDENTIFIED BY 'CHANGE_ME_other';
GRANT SELECT, SHOW VIEW, TRIGGER, LOCK TABLES, EVENT, PROCESS ON *.* TO 'seo_backup'@'localhost';
FLUSH PRIVILEGES;
SQL
```

For 8 GB RAM, in `/etc/mysql/mysql.conf.d/mysqld.cnf`: `innodb_buffer_pool_size = 2G`, `innodb_log_file_size = 256M` (or `innodb_redo_log_capacity = 512M` on 8.0.30+), `max_connections = 100`.

## 4. Application

```bash
sudo adduser --disabled-password deploy
sudo mkdir -p /var/www/seo-platform/{releases,shared/storage}
sudo chown -R deploy:www-data /var/www/seo-platform
sudo -iu deploy
cd /var/www/seo-platform
git clone <your-repo-url> releases/initial
ln -sfn /var/www/seo-platform/releases/initial current
cp -r current/storage/* shared/storage/ && rm -rf current/storage && ln -s /var/www/seo-platform/shared/storage current/storage
cp current/.env.example shared/.env && ln -s /var/www/seo-platform/shared/.env current/.env
cd current
composer install --no-dev --optimize-autoloader
npm ci --ignore-scripts && npm run build && rm -rf node_modules
php artisan key:generate          # BACK UP .env: APP_KEY decrypts stored API secrets
nano .env                         # DB_*, REDIS_PASSWORD, MAIL_*, APP_URL
php artisan migrate --force
SEO_OWNER_PASSWORD='choose-a-strong-one' php artisan db:seed --force
php artisan optimize
chmod -R ug+rwX /var/www/seo-platform/shared/storage
```

The seeder creates the owner (`arvind@intelliworkz.tech`) and four **inactive** team seats. In the app go to Team → edit each seat (name + real e-mail) → tick Active → "Reset password" to e-mail them an invite. There is no seat limit; add more at any time.

### E-mail

Any Laravel mail transport works; set it in `.env`:

| Provider | `.env` |
|---|---|
| Google Workspace / Microsoft 365 SMTP | `MAIL_MAILER=smtp`, `MAIL_HOST=smtp.gmail.com` / `smtp.office365.com`, `MAIL_PORT=587`, app password |
| Amazon SES | `MAIL_MAILER=ses` + `AWS_*` keys (`composer require aws/aws-sdk-php`) |
| Postmark / Resend / Mailgun | `MAIL_MAILER=postmark` etc. + the provider token (`composer require symfony/postmark-mailer` …) |

Use a sending domain with SPF, DKIM and DMARC records so alerts don't land in spam. After deploying, System → "Send test e-mail".

## 5. Web server and TLS

```bash
sudo cp /var/www/seo-platform/current/deploy/nginx-seo-platform.conf /etc/nginx/sites-available/seo-platform
sudo ln -s /etc/nginx/sites-available/seo-platform /etc/nginx/sites-enabled/ && sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
sudo apt -y install certbot python3-certbot-nginx && sudo certbot --nginx -d seo.intelliworkz.tech
```

The platform is internal: consider the `allow/deny` block in the Nginx file (office/VPN IPs only), or put it behind Cloudflare Access. Logins are rate-limited (5/min per e-mail+IP).

## 6. Queue workers (Supervisor)

```bash
sudo cp /var/www/seo-platform/current/deploy/supervisor-seo-platform.conf /etc/supervisor/conf.d/seo-platform.conf
sudo supervisorctl reread && sudo supervisorctl update && sudo supervisorctl status
```

Three isolated worker groups:

| Group | Queues | Connection (`retry_after`) | Why |
|---|---|---|---|
| `seo-fast` ×2 | `uptime`, `default` (alerts) | `redis` (90 s) | Uptime checks and alerts never wait behind crawls |
| `seo-crawl` ×3 | `crawl`, `audit` | `redis-long` (1260 s) | Crawl batches/audits can run for minutes |
| `seo-reports` ×1 | `reports`, `integrations` | `redis-long` (1260 s) | PDF rendering is memory-heavy; API syncs are quota-bound |

`retry_after` must stay larger than the longest job `--timeout` (1200 s), or a slow job could run twice. Keep `seo-crawl` numprocs ≥ Settings → "Max crawls running at the same time".

### Mobile rendering worker (phase 3 mobile checks)

Mobile page checks render pages in headless Chromium. It is free and runs on the same VPS:

```bash
cd /var/www/seo-platform/current/deploy/mobile-worker
npm ci --omit=dev
npx playwright-core install chromium      # or: sudo apt -y install chromium && export CHROMIUM_PATH=/usr/bin/chromium
sudo npx playwright-core install-deps chromium   # system libraries (once)
```

Keep `SEO_MOBILE_LOCAL=true` (default). Website → Site checks shows "Headless Chromium on this server" when it works. A run uses ~300 MB RAM for under a minute per site; it is scheduled weekly (Wednesday 03:00) on the `audit` queue.

**Hosting that cannot run Chromium (cPanel):** run the same folder on any small VPS or office PC with Node 18+:

```bash
MOBILE_WORKER_TOKEN=$(openssl rand -hex 24) PORT=8787 node server.mjs   # put it behind HTTPS (nginx/Caddy) or a private network
```

then set Settings → Site checks & workflow → **Mobile worker URL** (`https://worker-host/check`) and the same token. The worker only loads public pages and returns findings and screenshots; it never clicks or submits. If neither is available, mobile checks show **unsupported** and nothing is reported as passing.

### Outbound access needed by phase 3

- `https://rdap.org` (and the registry it redirects to) for domain expiry. Free; no key. If blocked, the domain shows "Unavailable" with the error and you can enter the date manually.
- The client websites themselves (already needed for crawling) for form checks.

## 7. Scheduler (cron)

```bash
sudo -iu deploy crontab -e     # paste deploy/crontab.txt
```

One cron line runs `schedule:run` every minute. Every schedule lives in `routes/console.php`:

| When (IST) | Task |
|---|---|
| every minute | scheduler + queue heartbeats, due uptime checks |
| every 5 min | due crawls, component health check (alerts owner, de-duplicated), external watchdog ping |
| every 10 / 30 min | stale-crawl recovery / critical watch (each site every 6 h) |
| daily 06:10, 06:45, 07:30 | URL Inspection, traffic & keyword drop check, blog sitemap scan + blog target reminders |
| weekdays 09:30 | overdue issue/task reminders to assignees |
| daily 03:30, 05:30, 05:45, 06:30, 07:10 | retention, Search Console, GA4, target actuals, SSL expiry |
| Sunday 04:00 | PageSpeed tests |
| Monday 09:00 | weekly digest e-mail |
| 3rd of month 06:00 | monthly PDF reports for every active site + portfolio, e-mailed when done (3rd because Search Console data lags ~2 days) |

## 8. Backups

`deploy/backup.sh` (nightly via cron) does:

1. `mysqldump --single-transaction` (no app downtime), gzip.
2. Archives `storage/app/private` (report PDFs, logo) and `.env` (contains `APP_KEY` — without it stored API keys cannot be decrypted).
3. Verifies both archives, keeps 14 daily + 12 monthly copies.
4. Copies off-site with rclone if a remote named `offsite` exists.

Setup:

```bash
sudo mkdir -p /var/backups/seo-platform && sudo chown deploy /var/backups/seo-platform
sudo -iu deploy bash -c 'printf "[client]\nuser=seo_backup\npassword=CHANGE_ME_other\n" > ~/.my.cnf && chmod 600 ~/.my.cnf'
sudo apt -y install rclone && sudo -iu deploy rclone config     # create remote "offsite" (Backblaze B2 / S3 / Google Drive)
sudo -iu deploy /var/www/seo-platform/current/deploy/backup.sh  # run once now
```

**Restore:** `deploy/restore.sh <db-….sql.gz> <files-….tar.gz>`. It puts the app in maintenance mode, stops workers, restores, migrates, and restarts. Test a restore on a scratch VPS once a quarter. A backup that has never been restored is untested.

Also enable your VPS provider's weekly snapshot as a second layer.

## 9. Monitoring the platform itself

See also Settings → Monitoring & alerts (thresholds, Healthchecks.io ping URL, secret status URL) and the System page (status, last success, next expected run and reason for every component).


- **Inside the app:** System page plus a check every 15 minutes. It e-mails the owner (at most every 6 hours per problem set) when the scheduler stops, a queue stops processing, jobs fail, e-mails fail, Redis is down or the disk is over 85 % full.
- **Outside the app:** if the whole VPS is down it cannot e-mail you. Add a free external monitor (UptimeRobot, Better Stack, Healthchecks.io) on `https://seo.intelliworkz.tech/up`, Laravel's built-in health route.
- Logs: `storage/logs/laravel-YYYY-MM-DD.log` (30 days), worker logs rotated by Supervisor; install `deploy/logrotate-seo-platform` to `/etc/logrotate.d/`.

## 10. Releases

```bash
sudo -iu deploy /var/www/seo-platform/current/deploy/deploy.sh main
```

It builds a fresh release directory, runs migrations, switches the `current` symlink, reloads PHP-FPM and runs `queue:restart` (workers finish their current job, then load the new code). It keeps 5 old releases; to roll back, point `current` at the previous one and run `php artisan queue:restart`.

Allow `deploy` to reload FPM without a password: `deploy ALL=NOPASSWD: /bin/systemctl reload php8.4-fpm, /usr/bin/supervisorctl` in `/etc/sudoers.d/deploy`.

## 11. Production checklist

- [ ] `APP_ENV=production`, `APP_DEBUG=false`, `APP_URL=https://…`
- [ ] `SEO_CRAWL_ALLOW_PRIVATE_IPS=false` (SSRF guard: the crawler refuses internal IPs)
- [ ] `SESSION_SECURE_COOKIE=true`, HTTPS working, owner password changed
- [ ] Supervisor: `sudo supervisorctl status` shows 6 RUNNING processes
- [ ] System page: all green within 2 minutes of cron starting
- [ ] Test e-mail received; SPF/DKIM pass
- [ ] Backup ran, off-site copy visible, restore tested
- [ ] External uptime monitor on `/up`
- [ ] Settings → Branding: logo, colours, footer
- [ ] Settings → Integrations: PageSpeed key, Google service account (optional)
- [ ] Mobile worker installed (`deploy/mobile-worker`), System → Site-check services shows "local" or "worker"
- [ ] Per website: approved contact details, inquiry forms (Admin approves test submissions per form), staging exceptions
