ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): URL-swap tool — safe, previewable site URL changes
Juan Denis57a7b7b3e687
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex e8d25250..9399b971 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -1087,6 +1087,40 @@ def search_replace(app_id):return jsonify(result), 200 if result['success'] else 400+@wordpress_bp.route('/sites/<int:app_id>/url/preview', methods=['POST'])+@jwt_required()+@admin_required+def preview_site_url(app_id):+ """Dry-run a site URL change: per-pair replacement counts, no mutation."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ data = request.get_json() or {}+ new_url = data.get('new_url')+ if not new_url:+ return jsonify({'error': 'new_url is required'}), 400+ result = WordPressService.preview_url_change(app, new_url)+ return jsonify(result), 200 if result.get('success') else 400+++@wordpress_bp.route('/sites/<int:app_id>/url', methods=['POST'])+@jwt_required()+@admin_required+def change_site_url(app_id):+ """Change a site's URL end to end: backup, serialization-safe DB rewrite,+ home/siteurl + cache flush, then re-point the Domain row + nginx vhost."""+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ data = request.get_json() or {}+ new_url = data.get('new_url')+ if not new_url:+ return jsonify({'error': 'new_url is required'}), 400+ keep_old = data.get('keep_old_redirect', True)+ result = WordPressService.change_site_url(app, new_url, keep_old_redirect=keep_old)+ return jsonify(result), 200 if result.get('success') else 400++@wordpress_bp.route('/sites/<int:app_id>/optimize', methods=['POST'])@jwt_required()@admin_requireddiff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex 1a08ca4f..d4461d4f 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -748,6 +748,188 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]result = cls.wp_cli(path, cmd)return result+ # ── URL swap tool ────────────────────────────────────────────────────────+ # Changing a WordPress site's URL is not a single UPDATE: the URL is embedded+ # across wp_options, post content, and PHP-serialized blobs whose byte-length+ # prefixes break under a naive REPLACE. WP-CLI `search-replace` is+ # serialization-safe, so it is the engine here (the pure-SQL path in+ # db_sync_service is the fallback for offline dumps only). We dry-run first,+ # back up before mutating, and roll back on failure.++ @staticmethod+ def _normalize_url(url: str) -> Optional[str]:+ """Canonicalise a user-supplied URL to ``scheme://host[/path]`` with no+ trailing slash. Returns None if it isn't a usable http(s) URL."""+ import re+ from urllib.parse import urlparse+ if not url:+ return None+ url = url.strip().rstrip('/')+ if '://' not in url:+ url = 'http://' + url+ p = urlparse(url)+ if p.scheme not in ('http', 'https') or not p.netloc:+ return None+ # Reject obviously-invalid hosts (spaces, etc.); allow hostname[:port].+ if not re.match(r'^[A-Za-z0-9.\-]+(:\d+)?$', p.netloc):+ return None+ return f'{p.scheme}://{p.netloc}{p.path.rstrip("/")}'++ @staticmethod+ def _host_of(url: str) -> str:+ from urllib.parse import urlparse+ return urlparse(url).netloc++ @classmethod+ def _url_swap_pairs(cls, old_url: str, new_url: str) -> List[tuple]:+ """search→replace pairs for a URL change: the full URL (covers scheme+ changes) plus a host-only pair (covers protocol-relative and bare-host+ references) when the host actually changes."""+ pairs = [(old_url, new_url)]+ old_host, new_host = cls._host_of(old_url), cls._host_of(new_url)+ if old_host and new_host and old_host != new_host:+ pairs.append((old_host, new_host))+ return pairs++ @staticmethod+ def _parse_sr_count(output: str) -> int:+ """Pull the replacement total out of WP-CLI search-replace output+ ('Success: 12 replacements to be made.' / 'Success: Made 12 replacements.')."""+ import re+ if not output:+ return 0+ for line in output.splitlines():+ if 'Success' in line:+ m = re.search(r'(\d[\d,]*)\s+replacement', line)+ if m:+ return int(m.group(1).replace(',', ''))+ return 0++ @classmethod+ def _site_current_url(cls, app) -> Optional[str]:+ """The site's live URL: prefer WordPress's own stored siteurl (source of+ truth for what must be search-replaced), else the canonical domain/port."""+ if app and app.root_path:+ res = cls.wp_cli(app.root_path, ['option', 'get', 'siteurl'])+ if res.get('success') and (res.get('output') or '').strip():+ return cls._normalize_url(res['output'].strip())+ return cls._canonical_site_url(app) if app else None++ @classmethod+ def preview_url_change(cls, app, new_url: str) -> Dict:+ """Dry-run a URL change: per-pair replacement counts, no mutation."""+ if not app or not app.root_path:+ return {'success': False, 'error': 'Site has no application/root path'}+ new_url = cls._normalize_url(new_url)+ if not new_url:+ return {'success': False, 'error': 'A valid new URL (including http:// or https://) is required'}+ old_url = cls._site_current_url(app)+ if not old_url:+ return {'success': False, 'error': 'Could not determine the current site URL'}+ if new_url == old_url:+ return {'success': False, 'error': 'The new URL is the same as the current one'}++ rows, total = [], 0+ for search, replace in cls._url_swap_pairs(old_url, new_url):+ res = cls.wp_cli(app.root_path, ['search-replace', search, replace,+ '--all-tables', '--skip-columns=guid',+ '--dry-run', '--report-changed-only'])+ if not res.get('success'):+ return {'success': False, 'error': res.get('error') or 'Preview failed',+ 'current_url': old_url, 'new_url': new_url}+ count = cls._parse_sr_count(res.get('output'))+ total += count+ rows.append({'search': search, 'replace': replace, 'replacements': count})+ return {'success': True, 'current_url': old_url, 'new_url': new_url,+ 'pairs': rows, 'total': total}++ @classmethod+ def change_site_url(cls, app, new_url: str, keep_old_redirect: bool = True) -> Dict:+ """Change a site's URL end to end: back up, serialization-safe DB rewrite,+ update home/siteurl, flush caches, then re-point the Domain row + nginx+ vhost. Rolls the database back from the backup if the rewrite fails.++ With ``keep_old_redirect`` the previous host keeps resolving (its vhost+ entry stays) so WordPress 301s it to the new canonical URL.+ """+ if not app or not app.root_path:+ return {'success': False, 'error': 'Site has no application/root path'}+ new_url = cls._normalize_url(new_url)+ if not new_url:+ return {'success': False, 'error': 'A valid new URL (including http:// or https://) is required'}+ old_url = cls._site_current_url(app)+ if not old_url:+ return {'success': False, 'error': 'Could not determine the current site URL'}+ if new_url == old_url:+ return {'success': False, 'error': 'The new URL is the same as the current one'}++ # 1) Backup first — this is the rollback point.+ backup = cls.backup_wordpress(app.root_path, include_db=True)+ if not backup.get('success'):+ return {'success': False, 'error': f"Backup failed, aborting URL change: {backup.get('error')}"}++ # 2) Serialization-safe DB rewrite, then finalize options + caches.+ total = 0+ try:+ for search, replace in cls._url_swap_pairs(old_url, new_url):+ res = cls.wp_cli(app.root_path, ['search-replace', search, replace,+ '--all-tables', '--skip-columns=guid'])+ if not res.get('success'):+ raise RuntimeError(res.get('error') or 'search-replace failed')+ total += cls._parse_sr_count(res.get('output'))+ cls.wp_cli(app.root_path, ['option', 'update', 'home', new_url])+ cls.wp_cli(app.root_path, ['option', 'update', 'siteurl', new_url])+ cls.wp_cli(app.root_path, ['cache', 'flush'])+ cls.wp_cli(app.root_path, ['rewrite', 'flush'])+ except Exception as e:+ restore = cls.restore_backup(backup['backup_name'], app.root_path)+ return {'success': False,+ 'error': f'URL change failed and the database was rolled back: {e}',+ 'rolled_back': restore.get('success', False),+ 'backup': backup['backup_name']}++ # 3) Re-point routing (best-effort; the DB change has already succeeded).+ warnings = []+ new_host = cls._host_of(new_url)+ rp = cls._repoint_primary_domain(app, new_host, keep_old=keep_old_redirect)+ if rp:+ warnings.append(rp)+ vhost = cls._write_app_vhost(app)+ if vhost.get('warning'):+ warnings.append(vhost['warning'])++ return {'success': True, 'old_url': old_url, 'new_url': new_url,+ 'replacements': total, 'backup': backup['backup_name'],+ 'kept_old_host': keep_old_redirect,+ 'warning': '; '.join(warnings) if warnings else None}++ @classmethod+ def _repoint_primary_domain(cls, app, new_host: str, keep_old: bool = True) -> Optional[str]:+ """Make ``new_host`` the app's primary Domain. With ``keep_old`` the other+ host rows are demoted (kept, so they still resolve); otherwise removed.+ Returns a warning string on failure, else None."""+ from app import db+ from app.models.domain import Domain+ if not new_host:+ return None+ try:+ found_new = False+ for d in Domain.query.filter_by(application_id=app.id).all():+ if d.name == new_host:+ d.is_primary = True+ found_new = True+ elif keep_old:+ d.is_primary = False+ else:+ db.session.delete(d)+ if not found_new:+ db.session.add(Domain(name=new_host, is_primary=True, application_id=app.id))+ db.session.commit()+ return None+ except Exception as e:+ db.session.rollback()+ return f'could not update domain rows: {e}'+@classmethoddef optimize_database(cls, path: str) -> Dict:"""Optimize WordPress database."""@@ -1612,7 +1794,6 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]"""from app import dbfrom app.models.domain import Domain- from app.services.nginx_service import NginxServiceif not site_host:return {'domain': None, 'nginx': None, 'warning': None}@@ -1627,25 +1808,37 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]db.session.rollback()warning = f'could not record domain {site_host}: {e}'- nginx_result = None- if app.port:- try:- domains = [d.name for d in Domain.query.filter_by(application_id=app.id).all()] or [site_host]- nginx_result = NginxService.create_site(- name=app.name, app_type='docker', domains=domains,- root_path=app.root_path or '', port=app.port,- )- if nginx_result.get('success'):- en = NginxService.enable_site(app.name)- if not en.get('success'):- nginx_result['warning'] = f"vhost written but not enabled: {en.get('error')}"- else:- msg = f"nginx vhost not created: {nginx_result.get('error')}"- warning = (warning + '; ' + msg) if warning else msg- except Exception as e:- msg = f'nginx vhost error: {e}'- warning = (warning + '; ' + msg) if warning else msg- return {'domain': site_host, 'nginx': nginx_result, 'warning': warning}+ v = cls._write_app_vhost(app)+ if v.get('warning'):+ warning = (warning + '; ' + v['warning']) if warning else v['warning']+ return {'domain': site_host, 'nginx': v.get('nginx'), 'warning': warning}++ @classmethod+ def _write_app_vhost(cls, app) -> Dict:+ """Write + enable the nginx reverse-proxy vhost for a docker app from its+ current Domain rows (server_name = every domain). Best-effort and never+ raises; returns ``{'nginx', 'warning'}``."""+ from app.models.domain import Domain+ from app.services.nginx_service import NginxService++ if not app.port:+ return {'nginx': None, 'warning': None}+ domains = [d.name for d in Domain.query.filter_by(application_id=app.id).all()]+ if not domains:+ return {'nginx': None, 'warning': None}+ try:+ res = NginxService.create_site(+ name=app.name, app_type='docker', domains=domains,+ root_path=app.root_path or '', port=app.port,+ )+ if res.get('success'):+ en = NginxService.enable_site(app.name)+ if not en.get('success'):+ res['warning'] = f"vhost written but not enabled: {en.get('error')}"+ return {'nginx': res, 'warning': None}+ return {'nginx': res, 'warning': f"nginx vhost not created: {res.get('error')}"}+ except Exception as e:+ return {'nginx': None, 'warning': f'nginx vhost error: {e}'}@classmethoddef _canonical_site_url(cls, app) -> str:diff --git a/backend/tests/test_url_swap.py b/backend/tests/test_url_swap.pynew file mode 100644index 00000000..70fcf28b--- /dev/null+++ b/backend/tests/test_url_swap.py@@ -0,0 +1,216 @@+"""Phase 2 proving tests — the WordPress URL-swap tool.++Changing a site's URL is a serialization-safe DB rewrite (WP-CLI search-replace),+backed up first and rolled back on failure, then a Domain/nginx re-point.+"""+++def _mk_user(db, username='owner'):+ from app.models import User+ from werkzeug.security import generate_password_hash+ u = User(email=f'{username}@test.local', username=username,+ password_hash=generate_password_hash('x'),+ role=User.ROLE_ADMIN, is_active=True)+ db.session.add(u)+ db.session.commit()+ return u+++def _mk_site_app(db, user_id, name='blog', port=8300, host='blog.lvh.me'):+ from app.models import Application+ from app.models.domain import Domain+ a = Application(name=name, app_type='docker', user_id=user_id,+ root_path=f'/srv/{name}', port=port)+ db.session.add(a)+ db.session.commit()+ db.session.add(Domain(name=host, is_primary=True, application_id=a.id))+ db.session.commit()+ return a+++# ── pure helpers ────────────────────────────────────────────────────────────++def test_normalize_url():+ from app.services.wordpress_service import WordPressService+ assert WordPressService._normalize_url('example.com') == 'http://example.com'+ assert WordPressService._normalize_url('https://example.com/') == 'https://example.com'+ assert WordPressService._normalize_url(' https://a.com/blog/ ') == 'https://a.com/blog'+ assert WordPressService._normalize_url('not a url') is None+ assert WordPressService._normalize_url('') is None+++def test_url_swap_pairs():+ from app.services.wordpress_service import WordPressService+ # Host change -> full-URL pair (covers scheme) + host-only pair.+ assert WordPressService._url_swap_pairs('http://old.com', 'https://new.com') == [+ ('http://old.com', 'https://new.com'), ('old.com', 'new.com')]+ # Scheme-only change -> single full-URL pair (same host).+ assert WordPressService._url_swap_pairs('http://a.com', 'https://a.com') == [+ ('http://a.com', 'https://a.com')]+++def test_parse_sr_count():+ from app.services.wordpress_service import WordPressService+ assert WordPressService._parse_sr_count('Success: 12 replacements to be made.') == 12+ assert WordPressService._parse_sr_count('Table\tx\nSuccess: Made 1,234 replacements.') == 1234+ assert WordPressService._parse_sr_count('') == 0+ assert WordPressService._parse_sr_count('nothing here') == 0+++# ── preview ─────────────────────────────────────────────────────────────────++def test_preview_counts_per_pair(app, monkeypatch):+ from app import db+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db)+ app_row = _mk_site_app(db, user.id, host='old.lvh.me')++ def fake_wp_cli(cls, path, command, *a, **k):+ if command[:2] == ['option', 'get']:+ return {'success': True, 'output': 'http://old.lvh.me\n'}+ if command[0] == 'search-replace':+ return {'success': True, 'output': 'Success: 5 replacements to be made.'}+ return {'success': True, 'output': ''}++ monkeypatch.setattr(WordPressService, 'wp_cli', classmethod(fake_wp_cli))++ res = WordPressService.preview_url_change(app_row, 'http://new.lvh.me')+ assert res['success'] is True+ assert res['current_url'] == 'http://old.lvh.me'+ assert res['new_url'] == 'http://new.lvh.me'+ assert len(res['pairs']) == 2 # full URL + host-only+ assert res['total'] == 10 # 5 per pair+++def test_preview_rejects_same_url(app, monkeypatch):+ from app import db+ from app.services.wordpress_service import WordPressService+ user = _mk_user(db, 'o2')+ app_row = _mk_site_app(db, user.id, host='same.lvh.me')+ monkeypatch.setattr(WordPressService, 'wp_cli',+ classmethod(lambda cls, path, command, *a, **k: {'success': True, 'output': 'http://same.lvh.me'}))+ res = WordPressService.preview_url_change(app_row, 'http://same.lvh.me')+ assert res['success'] is False+ assert 'same' in res['error'].lower()+++# ── apply ───────────────────────────────────────────────────────────────────++def test_change_url_happy_path_repoints_domain(app, monkeypatch):+ from app import db+ from app.models.domain import Domain+ from app.services import nginx_service+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db, 'o3')+ app_row = _mk_site_app(db, user.id, name='shop', host='old.lvh.me')++ def fake_wp_cli(cls, path, command, *a, **k):+ if command[:2] == ['option', 'get']:+ return {'success': True, 'output': 'http://old.lvh.me'}+ if command[0] == 'search-replace':+ return {'success': True, 'output': 'Success: Made 6 replacements.'}+ return {'success': True, 'output': ''}++ monkeypatch.setattr(WordPressService, 'wp_cli', classmethod(fake_wp_cli))+ monkeypatch.setattr(WordPressService, 'backup_wordpress',+ classmethod(lambda cls, path, include_db=True: {'success': True, 'backup_name': 'bk1'}))+ monkeypatch.setattr(nginx_service.NginxService, 'create_site',+ classmethod(lambda cls, **kw: {'success': True}))+ monkeypatch.setattr(nginx_service.NginxService, 'enable_site',+ classmethod(lambda cls, name: {'success': True}))++ res = WordPressService.change_site_url(app_row, 'https://new.example.com', keep_old_redirect=False)+ assert res['success'] is True+ assert res['old_url'] == 'http://old.lvh.me'+ assert res['new_url'] == 'https://new.example.com'+ assert res['replacements'] == 12 # 6 per pair * 2 pairs (host changed)+ assert res['backup'] == 'bk1'++ # Domain re-pointed: new host primary, old removed (keep_old_redirect=False).+ names = {d.name: d.is_primary for d in Domain.query.filter_by(application_id=app_row.id).all()}+ assert names == {'new.example.com': True}+++def test_change_url_rolls_back_on_failure(app, monkeypatch):+ from app import db+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db, 'o4')+ app_row = _mk_site_app(db, user.id, name='blogx', host='old.lvh.me')++ restored = {'called': False}++ def fake_wp_cli(cls, path, command, *a, **k):+ if command[:2] == ['option', 'get']:+ return {'success': True, 'output': 'http://old.lvh.me'}+ if command[0] == 'search-replace':+ return {'success': False, 'error': 'boom'}+ return {'success': True, 'output': ''}++ def fake_restore(cls, name, target):+ restored['called'] = True+ return {'success': True}++ monkeypatch.setattr(WordPressService, 'wp_cli', classmethod(fake_wp_cli))+ monkeypatch.setattr(WordPressService, 'backup_wordpress',+ classmethod(lambda cls, path, include_db=True: {'success': True, 'backup_name': 'bk2'}))+ monkeypatch.setattr(WordPressService, 'restore_backup', classmethod(fake_restore))++ res = WordPressService.change_site_url(app_row, 'https://new.example.com')+ assert res['success'] is False+ assert restored['called'] is True+ assert res['rolled_back'] is True+ assert 'boom' in res['error']+++def test_change_url_aborts_if_backup_fails(app, monkeypatch):+ from app import db+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db, 'o5')+ app_row = _mk_site_app(db, user.id, name='blogy', host='old.lvh.me')++ monkeypatch.setattr(WordPressService, 'wp_cli',+ classmethod(lambda cls, path, command, *a, **k: {'success': True, 'output': 'http://old.lvh.me'}))+ monkeypatch.setattr(WordPressService, 'backup_wordpress',+ classmethod(lambda cls, path, include_db=True: {'success': False, 'error': 'disk full'}))++ res = WordPressService.change_site_url(app_row, 'https://new.example.com')+ assert res['success'] is False+ assert 'backup failed' in res['error'].lower()+++def test_repoint_keep_old_demotes_but_keeps(app):+ from app import db+ from app.models.domain import Domain+ from app.services.wordpress_service import WordPressService++ user = _mk_user(db, 'o6')+ app_row = _mk_site_app(db, user.id, name='keepblog', host='old.lvh.me')++ warn = WordPressService._repoint_primary_domain(app_row, 'new.lvh.me', keep_old=True)+ assert warn is None+ rows = {d.name: d.is_primary for d in Domain.query.filter_by(application_id=app_row.id).all()}+ assert rows == {'old.lvh.me': False, 'new.lvh.me': True}+++# ── API wiring ──────────────────────────────────────────────────────────────++def test_url_preview_api_smoke(app, client, auth_headers, monkeypatch):+ from app import db+ from app.models import User+ from app.services.wordpress_service import WordPressService++ admin = User.query.filter_by(username='testadmin').first()+ app_row = _mk_site_app(db, admin.id, name='apisite', host='api.lvh.me')+ monkeypatch.setattr(WordPressService, 'preview_url_change',+ classmethod(lambda cls, a, new_url: {'success': True, 'total': 3, 'pairs': [],+ 'current_url': 'http://api.lvh.me', 'new_url': new_url}))+ r = client.post(f'/api/v1/wordpress/sites/{app_row.id}/url/preview',+ json={'new_url': 'http://x.com'}, headers=auth_headers)+ assert r.status_code == 200+ body = r.get_json()+ assert body['total'] == 3+ assert body['new_url'] == 'http://x.com'diff --git a/frontend/src/components/wordpress/ChangeUrlModal.jsx b/frontend/src/components/wordpress/ChangeUrlModal.jsxnew file mode 100644index 00000000..b9faae6e--- /dev/null+++ b/frontend/src/components/wordpress/ChangeUrlModal.jsx@@ -0,0 +1,151 @@+import { useState, useEffect } from 'react';+import { Globe, AlertTriangle, ArrowRight } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Switch } from '@/components/ui/switch';+import wordpressApi from '../../services/wordpress';+import { useToast } from '../../contexts/ToastContext';++// Change a WordPress site's URL safely: a debounced dry-run preview of the DB+// rewrite, then a backed-up, serialization-safe apply (WP-CLI search-replace)+// on confirm. The backend re-points the Domain row + nginx vhost afterwards.+export default function ChangeUrlModal({ site, onClose, onChanged }) {+ const toast = useToast();+ const currentUrl = site.url || '';+ const [newUrl, setNewUrl] = useState(currentUrl);+ const [keepOld, setKeepOld] = useState(true);+ const [preview, setPreview] = useState(null);+ const [previewing, setPreviewing] = useState(false);+ const [applying, setApplying] = useState(false);++ const target = newUrl.trim();+ const dirty = target && target !== currentUrl;++ // Debounced dry-run preview whenever the target URL settles.+ useEffect(() => {+ if (!dirty) { setPreview(null); return undefined; }+ let cancelled = false;+ setPreviewing(true);+ const timer = setTimeout(async () => {+ try {+ const res = await wordpressApi.previewUrlChange(site.id, target);+ if (!cancelled) setPreview(res);+ } catch (err) {+ if (!cancelled) setPreview({ success: false, error: err.message || 'Preview failed' });+ } finally {+ if (!cancelled) setPreviewing(false);+ }+ }, 500);+ return () => { cancelled = true; clearTimeout(timer); };+ }, [target, dirty, site.id]);++ async function handleApply(e) {+ e?.preventDefault();+ if (!dirty || applying) return;+ setApplying(true);+ toast.info('Changing site URL — backing up and rewriting the database…', { duration: 5000 });+ try {+ const res = await wordpressApi.changeUrl(site.id, target, keepOld);+ if (res.success) {+ toast.success(`Site URL changed to ${res.new_url} (${res.replacements} replacement${res.replacements === 1 ? '' : 's'})`);+ if (res.warning) toast.warning(res.warning, { duration: 7000 });+ onChanged?.();+ onClose();+ } else {+ toast.error(res.error || 'Failed to change URL');+ }+ } catch (err) {+ toast.error(err.message || 'Failed to change URL');+ } finally {+ setApplying(false);+ }+ }++ return (+ <div className="modal-overlay" onClick={() => !applying && onClose()}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2><Globe size={18} /> Change Site URL</h2>+ <button className="modal-close" onClick={() => !applying && onClose()}>×</button>+ </div>+ <form onSubmit={handleApply}>+ <div className="wp-url-swap">+ <div className="wp-url-swap__warning">+ <AlertTriangle size={18} aria-hidden="true" />+ <span>+ This rewrites every reference to the site URL across the database+ (posts, options, serialized data) with a serialization-safe+ search-replace. A database backup is taken first and restored+ automatically if anything fails.+ </span>+ </div>++ <div className="wp-url-swap__fromto">+ <code>{currentUrl || '—'}</code>+ <ArrowRight size={15} aria-hidden="true" />+ <code className={dirty ? 'is-new' : ''}>{target || '—'}</code>+ </div>++ <div className="form-group">+ <Label htmlFor="wp-new-url">New URL</Label>+ <Input+ id="wp-new-url"+ type="text"+ value={newUrl}+ onChange={(e) => setNewUrl(e.target.value)}+ placeholder="https://example.com"+ disabled={applying}+ autoFocus+ />+ <span className="form-hint">+ Include http:// or https://. Point this hostname's DNS at the server first.+ </span>+ </div>++ <label className="wp-url-swap__keep">+ <Switch checked={keepOld} onCheckedChange={setKeepOld} disabled={applying} />+ <span>+ Keep the old address working+ <small>The previous host keeps resolving; WordPress 301-redirects it to the new URL.</small>+ </span>+ </label>++ {dirty && (+ <div className="wp-url-swap__preview">+ {previewing && <span className="form-hint">Previewing changes…</span>}+ {!previewing && preview?.success && (+ <>+ <div className="wp-url-swap__preview-total">+ {preview.total} database replacement{preview.total === 1 ? '' : 's'} will be made+ </div>+ <ul className="wp-url-swap__preview-pairs">+ {preview.pairs.map((p, i) => (+ <li key={i}>+ <code>{p.search}</code>+ <ArrowRight size={12} aria-hidden="true" />+ <code>{p.replace}</code>+ <span className="wp-url-swap__count">{p.replacements}</span>+ </li>+ ))}+ </ul>+ </>+ )}+ {!previewing && preview && !preview.success && (+ <div className="wp-url-swap__preview-error">{preview.error}</div>+ )}+ </div>+ )}+ </div>++ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={onClose} disabled={applying}>Cancel</Button>+ <Button type="submit" disabled={!dirty || applying}>+ {applying ? 'Changing…' : 'Change URL'}+ </Button>+ </div>+ </form>+ </div>+ </div>+ );+}diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 9a2054fc..d5c4c3bd 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -8,6 +8,7 @@ import api from '../services/api';import { useToast } from '../contexts/ToastContext';import { useLogsDrawer } from '../contexts/LogsDrawerContext';import { EnvironmentCard, SnapshotTable, GitConnectForm, CommitList, DiskUsageBar } from '../components/wordpress';+import ChangeUrlModal from '../components/wordpress/ChangeUrlModal';import { HealthDot } from '../components/wordpress/HealthStatusPanel';import { Pill, EnvTag, MetricCard, SegControl, ScoreGauge, ServiceTile } from '../components/ds';import { ErrorBoundary, ErrorState } from '../components/ErrorBoundary';@@ -154,6 +155,7 @@ const WordPressDetail = () => {const [activeTab, setActiveTab] = useTabParam(`/wordpress/${id}`, VALID_TABS);const [autoLoggingIn, setAutoLoggingIn] = useState(false);const [showCloneModal, setShowCloneModal] = useState(false);+ const [showChangeUrl, setShowChangeUrl] = useState(false);const [cloning, setCloning] = useState(false);const [cloneName, setCloneName] = useState('');const [clonedCreds, setClonedCreds] = useState(null);@@ -334,6 +336,14 @@ const WordPressDetail = () => {</Button></>)}+ <Button+ variant="ghost"+ onClick={() => setShowChangeUrl(true)}+ title="Change this site's URL (serialization-safe database rewrite + re-point routing)"+ >+ <Globe size={16} />+ Change URL+ </Button><Buttonvariant="ghost"onClick={() => setShowCloneModal(true)}@@ -487,6 +497,14 @@ const WordPressDetail = () => {</div></div>+ {showChangeUrl && (+ <ChangeUrlModal+ site={site}+ onClose={() => setShowChangeUrl(false)}+ onChanged={loadSite}+ />+ )}+{/* Clone Site Modal */}{showCloneModal && (<div className="modal-overlay" onClick={() => !cloning && setShowCloneModal(false)}>diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 81e57d2f..d8fed824 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -29,6 +29,18 @@ const wordpressApi = {getSite: (id) => api.request(`${BASE_PATH}/${id}`),+ // Preview a site URL change (dry-run: per-pair DB replacement counts, no mutation).+ previewUrlChange: (id, newUrl) => api.request(`${BASE_PATH}/${id}/url/preview`, {+ method: 'POST',+ body: { new_url: newUrl }+ }),++ // Change a site's URL: backup + serialization-safe DB rewrite + re-point routing.+ changeUrl: (id, newUrl, keepOldRedirect = true) => api.request(`${BASE_PATH}/${id}/url`, {+ method: 'POST',+ body: { new_url: newUrl, keep_old_redirect: keepOldRedirect }+ }),+// Replace the tag list for a site (agency organization labels)setTags: (id, tags) => api.request(`${BASE_PATH}/${id}/tags`, {method: 'PATCH',diff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scssindex 1bf52345..aa5b2bdf 100644--- a/frontend/src/styles/pages/_wordpress.scss+++ b/frontend/src/styles/pages/_wordpress.scss@@ -2799,3 +2799,118 @@}}}++// Change Site URL modal (URL-swap tool)+.wp-url-swap {+ display: flex;+ flex-direction: column;+ gap: 16px;+ padding: 4px 0 8px;++ &__warning {+ display: flex;+ gap: 10px;+ padding: 12px 14px;+ border-radius: var(--radius);+ background: var(--surface-2);+ border: 1px solid var(--border-soft);+ font-size: 12.5px;+ line-height: 1.5;+ color: var(--text-faint);++ svg { flex-shrink: 0; color: var(--amber); margin-top: 1px; }+ }++ &__fromto {+ display: flex;+ align-items: center;+ gap: 10px;+ flex-wrap: wrap;++ code {+ font-family: var(--mono);+ font-size: 12px;+ padding: 4px 8px;+ border-radius: 6px;+ background: var(--surface-2);+ border: 1px solid var(--border-soft);+ color: var(--text-faint);+ word-break: break-all;++ &.is-new { color: var(--green); border-color: var(--accent-dim); }+ }+ svg { color: var(--text-ghost); flex-shrink: 0; }+ }++ &__keep {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ cursor: pointer;++ > span {+ display: flex;+ flex-direction: column;+ font-size: 13px;+ font-weight: 500;+ }+ small {+ font-weight: 400;+ font-size: 11.5px;+ color: var(--text-faint);+ margin-top: 2px;+ }+ }++ &__preview {+ border-top: 1px solid var(--border-soft);+ padding-top: 12px;+ }++ &__preview-total {+ font-size: 13px;+ font-weight: 600;+ color: var(--text);+ margin-bottom: 8px;+ }++ &__preview-pairs {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;++ li {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 11.5px;++ code {+ font-family: var(--mono);+ color: var(--text-faint);+ word-break: break-all;+ }+ svg { color: var(--text-ghost); flex-shrink: 0; }+ }+ }++ &__count {+ margin-left: auto;+ font-family: var(--mono);+ font-size: 11px;+ padding: 1px 8px;+ border-radius: 999px;+ background: var(--surface-2);+ border: 1px solid var(--border-soft);+ color: var(--text-faint);+ flex-shrink: 0;+ }++ &__preview-error {+ font-size: 12.5px;+ color: var(--red);+ }+}