WordPress wp-config Site URL for a Headless Front End

In a headless WordPress setup, the wp-config site URL is easy to get wrong. Suppose you set WP_HOME to your front-end domain (Next.js, Astro, Nuxt…). Then wp-admin redirects to the wrong host, the REST API answers on a domain that does not run PHP, and logins break. Leave it on the CMS domain instead, and every permalink, the REST link field, the editor’s “View post” button and the sitemap all point to the backend that visitors should never see.

The fix is to keep the two URLs apart. WP_HOME and WP_SITEURL stay on the CMS host so WordPress can serve itself. A separate constant, DPC_FRONTEND_URL, holds the public URL for each environment. A small mu-plugin rewrites public links to that URL and sends anyone who lands on the CMS front end to the same path on your app.

The wp-config.php part

Set the URLs per environment. WP_ENVIRONMENT_TYPE comes from your host or .env, so the same file works on local, staging and production:

// wp-config.php, above "That's all, stop editing!"
$dpc_env = getenv( 'WP_ENVIRONMENT_TYPE' ) ?: 'production';

$dpc_urls = [
	'local'      => [ 'http://cms.test',             'http://localhost:3000' ],
	'staging'    => [ 'https://cms.staging.example.com', 'https://staging.example.com' ],
	'production' => [ 'https://cms.example.com',     'https://www.example.com' ],
];
[ $dpc_cms, $dpc_front ] = $dpc_urls[ $dpc_env ] ?? $dpc_urls['production'];

define( 'WP_ENVIRONMENT_TYPE', $dpc_env );
define( 'WP_HOME', $dpc_cms );      // WordPress itself lives here
define( 'WP_SITEURL', $dpc_cms );
define( 'DPC_FRONTEND_URL', $dpc_front ); // what visitors see

The snippet

Put this in an mu-plugin (wp-content/mu-plugins/dpc-headless-urls.php) so a theme switch cannot turn it off. It also runs as a single Scripts Organizer PHP block. If neither the constant nor an environment variable is set, it does nothing.

<?php
/**
 * Plugin Name: DPC Headless Front-End URLs
 * Description: Keeps WP_HOME on the CMS, points public links and visitors to DPC_FRONTEND_URL.
 */

function dpc_headless_frontend_url(): string {
	$url = '';
	if ( defined( 'DPC_FRONTEND_URL' ) ) {
		$url = (string) DPC_FRONTEND_URL;
	} elseif ( false !== getenv( 'DPC_FRONTEND_URL' ) ) {
		$url = (string) getenv( 'DPC_FRONTEND_URL' );
	}
	$url = (string) apply_filters( 'dpc_headless_frontend_url', $url );

	return untrailingslashit( esc_url_raw( $url, array( 'http', 'https' ) ) );
}

/** "https://host/path" -> "//host/path", so http/https mismatches still match. */
function dpc_headless_strip_scheme( string $url ): string {
	return (string) preg_replace( '#^https?:#i', '', $url );
}

/** Swap a URL that starts with $from (any scheme) for the same path on $to. */
function dpc_headless_replace_base( $url, string $from, string $to ) {
	if ( ! is_string( $url ) || '' === $from || '' === $to ) {
		return $url;
	}
	$bare_url  = dpc_headless_strip_scheme( $url );
	$bare_from = dpc_headless_strip_scheme( $from );
	if ( ! str_starts_with( strtolower( $bare_url ), strtolower( $bare_from ) ) ) {
		return $url;
	}
	$rest = substr( $bare_url, strlen( $bare_from ) );
	// Make sure "https://cms.example.com" does not match "https://cms.example.com.evil".
	if ( '' !== $rest && ! in_array( $rest[0], array( '/', '?', '#' ), true ) ) {
		return $url;
	}
	return $to . $rest;
}

/** Public links (permalinks, terms, authors, REST "link" field) go to the front end. */
function dpc_headless_to_frontend( $url ) {
	return dpc_headless_replace_base( $url, untrailingslashit( home_url() ), dpc_headless_frontend_url() );
}

/** Previews stay on the CMS, where the logged-in editor's cookie works. */
function dpc_headless_preview_to_cms( $url ) {
	return dpc_headless_replace_base( $url, dpc_headless_frontend_url(), untrailingslashit( home_url() ) );
}

foreach ( array( 'post_link', 'page_link', 'post_type_link', 'term_link', 'author_link' ) as $dpc_hook ) {
	add_filter( $dpc_hook, 'dpc_headless_to_frontend', 20 );
}
add_filter( 'preview_post_link', 'dpc_headless_preview_to_cms', 20 );

/** Where a front-end request on the CMS host should go, or null to serve it. */
function dpc_headless_redirect_target(): ?string {
	$frontend = dpc_headless_frontend_url();

	if ( '' === $frontend || is_admin() || wp_doing_ajax() || wp_doing_cron()
		|| ( defined( 'REST_REQUEST' ) && REST_REQUEST )
		|| is_preview() || is_customize_preview()
		|| is_feed() || is_robots() || get_query_var( 'sitemap' ) ) {
		return null;
	}
	if ( ! apply_filters( 'dpc_headless_redirect_enabled', true ) ) {
		return null;
	}

	$uri  = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
	$uri  = '/' . ltrim( $uri, '/' );
	$base = '/' . trim( (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ), '/' );

	// WordPress in a sub-folder: drop that folder from the path.
	if ( '/' !== $base && ( $uri === $base || str_starts_with( $uri, $base . '/' ) || str_starts_with( $uri, $base . '?' ) ) ) {
		$uri = '/' . ltrim( substr( $uri, strlen( $base ) ), '/' );
	}

	return $frontend . $uri;
}

function dpc_headless_maybe_redirect(): void {
	$target = dpc_headless_redirect_target();
	if ( $target ) {
		wp_redirect( $target, 302, 'DPC Headless' );
		exit;
	}
}
add_action( 'template_redirect', 'dpc_headless_maybe_redirect', 1 );

How it works

  • dpc_headless_frontend_url() reads DPC_FRONTEND_URL from wp-config. If the constant is missing, it reads the server environment instead. It cleans the value with esc_url_raw() and allows only http and https.
  • The link filters swap the home_url() prefix for the front-end URL. home_url() and site_url() stay unchanged, so wp-admin, login, admin-ajax.php and /wp-json/ keep working on the CMS host.
  • Matching ignores the scheme. A link that WordPress or a proxy turned from https into http (or the other way round) is still recognised, and a lookalike host such as cms.example.com.evil is never matched.
  • The REST API builds its link field with get_permalink(), so your front end gets the correct public URL without extra code.
  • Preview links go back to the CMS. The front-end domain can’t read the editor’s login cookie, so a preview there would show a 404 or the published version.
  • template_redirect sends real visitors to the same path on the front end. Previews, the Customizer, feeds, robots.txt, sitemaps, REST, AJAX and cron are left alone.

Customise it

  • Need different URLs per request, for example for a multilingual front end? Use the dpc_headless_frontend_url filter.
  • If your app has its own draft-mode route, change dpc_headless_preview_to_cms() so it returns that route. For example, use add_query_arg( 'id', ... , $frontend . '/api/preview' ) plus a secret that your app checks.
  • To let editors browse the CMS theme, return ! is_user_logged_in() from dpc_headless_redirect_enabled.

Gotchas

  • The redirect uses 302 on purpose. Change it to 301 only after you have checked every environment: browsers cache a 301, and a wrong one is hard to undo.
  • Keep the REST API public for the routes your front end fetches without logging in. If you lock it down as in WordPress REST API Restricted to Authenticated Users, give your app an application password.
  • Links already saved inside post content still use whatever URL the author pasted. If old CMS links are stored there, run wp search-replace once.
  • Your wp-config now differs per environment. Keep secrets in environment variables and keep debug output off in production, as shown in Hide Errors using wp-config file.

Snippet poll. Should this snippet be in the Scripts Organizer library for one-click import? 10 votes put it there.

0 of 10 votes

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You’ll also get DPlugins product updates. No spam, and you can unsubscribe anytime.

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You'll also get DPlugins product updates. No spam, and you can unsubscribe anytime.