Random Bright, Funny, Info, Deep Thoughts, AI Chats, and More

[
[
[

]
]
]

To redirect an entire domain to a new one while preserving your SEO rankings (link equity), a 301 Permanent Redirect is the industry standard.
Since you work with HTML and PHP, here are the most effective ways to implement this depending on your server environment.

  1. Apache Server (.htaccess)
    This is the most common method. Create or edit the .htaccess file in the root directory of your old domain.
    Option A: Simple Redirect (Whole Domain)
    Use this if you want every request on the old domain to go to the homepage of the new domain.
    Redirect 301 / https://new-domain.com/

Option B: Wildcard Redirect (Preserve URL Path)
Use this if you want old-domain.com/about to automatically go to new-domain.com/about. This is much better for SEO.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www.)?old-domain.com$ [NC]
RewriteRule ^(.*)$ https://new-domain.com/$1 [L,R=301]

  1. PHP Method
    If you don’t have access to server config files, you can use a PHP script. Place this code at the very top of your index.php (or a global header file) on the old domain.
    <?php
    // Calculate the new destination URL while preserving the path
    $new_domain = ‘https://new-domain.com&#8217;;
    $request_uri = $_SERVER[‘REQUEST_URI’];

header(“HTTP/1.1 301 Moved Permanently”);
header(“Location: ” . $new_domain . $request_uri);
exit();
?>

  1. Nginx Server
    If your server uses Nginx, you must edit your server block configuration (usually found in /etc/nginx/sites-available/).
    server {
    listen 80;
    server_name old-domain.com http://www.old-domain.com;
    return 301 https://new-domain.com$request_uri;
    }
  2. DNS / Cloudflare Method (Recommended)
    If you use Cloudflare, you can perform the redirect at the “Edge,” meaning the request never even hits your old server. This is the fastest method.
  • Go to Rules > Redirect Rules.
  • Click Create Rule.
  • Field: Hostname | Operator: Equals | Value: old-domain.com.
  • Type: Dynamic.
  • Expression: concat(“https://new-domain.com&#8221;, http.request.uri.path)
  • Status Code: 301.
    Key SEO Checklist for 2026
  • Keep the old domain: You must keep the registration for the old domain active for the redirect to work.
  • HTTPS: Ensure both the old and new domains have SSL certificates, or the redirect might trigger a browser security warning.
  • Update Google Search Console: Use the Change of Address Tool in GSC to notify Google that you have moved.
  • Duration: Keep 301 redirects active for at least one year (Google recommends this to ensure all signals are passed).
    Would you like me to generate a complete PHP script that also logs these redirects to a file for your records?

Here is a robust PHP script for your old domain. This script does two things: it performs the 301 redirect while preserving the URL path, and it logs the request to a text file so you can see which pages are still being accessed via the old domain.
index.php (for your old domain)
<?php
// 1. Configuration
$new_domain = ‘https://www.new-domain.com&#8217;; // Change this to your new domain
$log_file = ‘redirect_log.txt’; // Name of the log file

// 2. Get the current URL path and query string
$request_uri = $_SERVER[‘REQUEST_URI’];
$full_new_url = $new_domain . $request_uri;

// 3. Log the redirect (Optional but helpful)
$timestamp = date(‘Y-m-d H:i:s’);
$remote_ip = $_SERVER[‘REMOTE_ADDR’];
$log_entry = “[$timestamp] IP: $remote_ip | Path: $request_uri -> $full_new_url” . PHP_EOL;

// Append to log file (make sure the directory is writable)
file_put_contents($log_file, $log_entry, FILE_APPEND);

// 4. Perform the 301 Redirect
header(“HTTP/1.1 301 Moved Permanently”);
header(“Location: ” . $full_new_url);

// 5. Stop further script execution
exit();
?>

Implementation Steps

  • Backup: Always back up your existing files before replacing them.
  • Permissions: Ensure your server has write permissions for the directory so it can create the redirect_log.txt file.
  • Catch-All: For this PHP script to catch every request (e.g., old-domain.com/some-article), you usually need a tiny .htaccess file alongside it to route all traffic to this index.php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Why this is useful for you:

  • SEO Preservation: The 301 header tells search engines the move is permanent, transferring “link juice.”
  • Data Insights: By checking redirect_log.txt, you can identify which old backlinks are still active and perhaps reach out to those site owners to update their links to your new domain.
  • Cleanliness: It handles query strings (like ?id=123) automatically via the REQUEST_URI.
    Would you like me to help you draft the “Change of Address” notice for your Google Search Console setup?

To move a site effectively in 2026, Google Search Console (GSC) requires a specific sequence. Before using the “Change of Address” tool, you must ensure the technical foundations are set.
Here is a step-by-step guide and the draft you can use for your records.
1. The Pre-Migration Checklist
Before notifying Google, ensure the following are true:
* Verification: You have both the old and new domains verified as separate properties in Google Search Console.
* Redirects: Your 301 redirects (like the PHP script we created) are live and tested.
* Sitemaps: You have a sitemap ready for the new domain.
2. Using the “Change of Address” Tool
* Open the Old Domain property in GSC.
* Go to Settings (bottom left).
* Click on Change of Address.
* Select your New Domain from the list.
* Click Validate & Update. Google will test a few URLs to ensure your 301 redirects are working.
3. Draft: Migration Record / Internal Log
It is helpful to keep a record of this change for your own documentation or for your client if you are building this for someone else.
> Project: Domain Migration
> Date: January 2026
> Old URL: old-domain.com
> New URL: new-domain.com
> Migration Steps Taken:
>  * Technical: Implemented 301 redirects via PHP with server-side logging enabled.
>  * Security: SSL certificates installed on both domains to prevent “Insecure” warnings during transit.
>  * GSC: Notified Google via the Change of Address tool.
>  * Sitemap: Submitted new sitemap.xml to the new domain property.
> Note: Monitor redirect_log.txt for the next 30 days to identify high-traffic pages that may require manual backlink updates.
>
4. Pro-Tip: The “Double Sitemap” Strategy
To speed up the indexing of your new domain, keep your old sitemap active on the old domain for a few weeks.
Even though the URLs in that sitemap now redirect, it encourages Google’s crawlers to visit the old URLs more frequently, discover the 301 redirect, and update their index to the new domain faster.
Would you like me to create a PHP-based sitemap generator for your new domain to help with the re-indexing?
Since you build informational web pages in HTML and PHP, a dynamic PHP sitemap is the best way to go. It automatically updates whenever you add new articles, so you don’t have to manually edit an XML file.
Here is a clean, modern implementation for your new domain.
1. The PHP Sitemap Script (sitemap-gen.php)
Place this file in your root directory. It generates a valid XML sitemap by pulling data from an array (or you can easily connect it to a database later).
<?php
// Set the correct content type for XML
header(“Content-Type: application/xml; charset=utf-8”);

// Define your new domain
$base_url = “https://www.new-domain.com/&#8221;;

// In a real scenario, you could fetch these from your database
// For now, here is an array of your pages
$pages = [
    [‘url’ => ”, ‘priority’ => ‘1.0’, ‘change’ => ‘daily’],
    [‘url’ => ‘about-us.html’, ‘priority’ => ‘0.5’, ‘change’ => ‘monthly’],
    [‘url’ => ‘services.php’, ‘priority’ => ‘0.8’, ‘change’ => ‘weekly’],
    [‘url’ => ‘contact.html’, ‘priority’ => ‘0.5’, ‘change’ => ‘monthly’],
];

echo ‘<?xml version=”1.0″ encoding=”UTF-8″?>’;
echo ‘<urlset xmlns=”http://www.sitemaps.org/schemas/sitemap/0.9″>&#8217;;

foreach ($pages as $page) {
    echo ‘<url>’;
    echo ‘<loc>’ . $base_url . $page[‘url’] . ‘</loc>’;
    echo ‘<lastmod>’ . date(‘Y-m-d’) . ‘</lastmod>’;
    echo ‘<changefreq>’ . $page[‘change’] . ‘</changefreq>’;
    echo ‘<priority>’ . $page[‘priority’] . ‘</priority>’;
    echo ‘</url>’;
}

echo ‘</urlset>’;
?>

2. Make it look like a real .xml file
Search engines prefer to see /sitemap.xml. Since you are on a server that supports PHP, add this line to your new domain’s .htaccess file. It tells the server to run the PHP script whenever someone (or a bot) visits sitemap.xml.
RewriteEngine On
RewriteRule ^sitemap\.xml$ sitemap-gen.php [L]

3. SEO Best Practices for 2026
* Absolute URLs: Always use the full https://www&#8230; path in the <loc> tag.
* Update Frequency: Only use daily for your homepage or news pages. Use monthly for static pages like “Contact” to avoid wasting Google’s “crawl budget.”
* Robots.txt: Explicitly tell search engines where the sitemap is by adding this line to your robots.txt file:
   > Sitemap: https://www.new-domain.com/sitemap.xml
   >
Summary of your Domain Move
You now have a complete system:
* Old Domain: A PHP script that redirects users and logs who is still using the old links.
* Server: An .htaccess rule to handle the routing.
* New Domain: A dynamic sitemap to help Google index your new pages instantly.
Would you like me to show you how to connect the sitemap script to a MySQL database so it automatically includes every new article you publish?

Connecting your sitemap to a database is the “gold standard” for informational sites. It ensures that the moment you hit “publish” on a new article, it is immediately available for search engines to crawl without you touching a single line of code.
Here is how to update your sitemap-gen.php to pull from a MySQL database.

  1. Updated sitemap-gen.php with Database Connection
    This script assumes you have a table (e.g., articles) with columns for slug, updated_at, and importance.
    <?php
    header(“Content-Type: application/xml; charset=utf-8”);

// 1. Database Configuration
$host = ‘localhost’;
$db = ‘your_database_name’;
$user = ‘your_username’;
$pass = ‘your_password’;
$charset = ‘utf8mb4’;

$dsn = “mysql:host=$host;dbname=$db;charset=$charset”;
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];

try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
// In case of error, you can log it or exit
exit(‘Database connection failed.’);
}

// 2. Fetch your articles/pages
// We select the slug and the last modified date
$stmt = $pdo->query(“SELECT slug, updated_at, priority FROM articles WHERE status = ‘published’”);

$base_url = “https://www.new-domain.com/&#8221;;

echo ”;
echo ”;

// Add static homepage first
echo ”.$base_url.’1.0daily’;

// 3. Loop through database results
while ($row = $stmt->fetch()) {
echo ”; echo ” . $base_url . htmlspecialchars($row[‘slug’]) . ”; // Ensure date is in ISO 8601 format (YYYY-MM-DD) echo ” . date(‘Y-m-d’, strtotime($row[‘updated_at’])) . ”; echo ” . $row[‘priority’] . ”; echo ‘weekly’; echo ”;
}

echo ”;
?>

  1. Key Elements for Your Setup
  • PDO (PHP Data Objects): I used PDO instead of mysqli because it is more secure against SQL injection and is the modern standard for 2026.
  • The slug Column: This is the URL-friendly version of your title (e.g., how-to-redirect-domains).
  • Dynamic lastmod: Using the updated_at column from your DB is critical. It tells Google exactly when a page was last refreshed, which can trigger a re-crawl.
  1. Verification & Ping
    Once this is live, you can “ping” Google to let them know the sitemap has changed. Simply paste this into your browser (replacing the URL with your own):
    https://www.google.com/ping?sitemap=https://www.new-domain.com/sitemap.xml
    Summary of your “New Domain” Architecture
    | Component | Function |
    |—|—|
    | MySQL Table | Stores your article content and metadata. |
    | sitemap-gen.php | Automatically converts DB rows into Google-readable XML. |
    | .htaccess | Masks the .php extension to look like a standard .xml file. |
    | Robots.txt | Points the way for all search crawlers. |


Discover more from NathanLegakis.com

Subscribe to get the latest posts sent to your email.

Leave a Reply

Discover more from NathanLegakis.com

Subscribe now to keep reading and get access to the full archive.

Continue reading