How To Create a PHP Redirect (301, 302, and Dynamic Redirect Examples) Updated on December 9, 2025 by Carrie Smaha 10 Minutes, 54 Seconds to Read PHP redirects let you send users from one page to another using server-side code. In this tutorial, you’ll learn how to create 301 and 302 redirects in PHP, redirect after forms, enforce HTTPS, and handle conditional or dynamic redirects. It also covers common errors, testing methods, and best practices to keep your site fast, secure, and SEO-friendly. Redirects are one of the most important tools for keeping your website organized, secure, and SEO-friendly. If you ever move or rename pages, update your domain, or need to guide visitors to a new location, a redirect makes sure they get there automatically. While many users set up redirects in .htaccess or cPanel, you can also use PHP redirects directly in your code. This guide explains how PHP redirects work, when to use them, and provides step-by-step examples for both permanent (301) and temporary (302) redirects. What Is a PHP Redirect? If you’ve ever clicked on a link that quickly took you somewhere else, you’ve experienced a redirect in action. A PHP redirect uses server-side code to tell browsers to load a different web address instead of the one requested. It’s simple, powerful, and an essential tool when your website structure changes. A PHP redirect sends a user’s browser (and search engines) from one web address to another using the header() function. It works server-side, before the page content loads. Unlike HTML meta refresh or JavaScript redirects, PHP redirects happen before any HTML output. This makes them faster and more reliable for SEO and user experience. When used properly, PHP redirects ensure visitors and search engines always reach the correct destination. They’re especially valuable for dynamic or logic-based website setups. When To Use a PHP Redirect Before adding redirects, it’s important to understand when PHP is the right choice. PHP redirects are great when you need conditional or logic-based control rather than simple static rules. They’re especially useful for dynamic websites or marketing teams that update landing pages frequently. You might use PHP redirects when: You’ve changed the location of a page or file. You’ve migrated content from one domain to another. You want to redirect users after logging in or submitting a form. You need conditional logic. This could include redirecting users based on region, session, or device. For most static redirects, .htaccess is faster. But PHP redirects are ideal when you need flexibility or logic-based control that can’t be handled with simple rewrite rules. If your redirect requires decision-making or depends on user actions, PHP is the most flexible solution. It’s a good option when your redirect logic can’t be defined in simple patterns. How PHP Redirects Work Understanding how PHP redirects work helps prevent errors before they happen. Every redirect is built around a single PHP function that tells the browser to go somewhere else. This happens before the browser renders any content, so it must occur early in your code. The header() function in PHP sends an HTTP response header before any content is sent to the browser. To redirect, it uses a Location header: <?php header("Location: https://example.com/new-page.php"); exit(); ?><?php header("Location: https://example.com/new-page.php"); exit(); ?> Two key details: Always call exit() right after the header to stop script execution. The header() call must come before any HTML output, including whitespace. If you accidentally place it after page content, you’ll get an error like: Warning: Cannot modify header information - headers already sentWarning: Cannot modify header information - headers already sent In short, PHP redirects must run before the browser receives any output. Following these simple rules ensures clean, fast redirects without unexpected behavior.y output. Following these simple rules ensures clean, fast redirects without unexpected behavior. Types of PHP Redirects Different redirects serve different purposes, and knowing which to use prevents SEO and usability issues. PHP supports both permanent and temporary redirects through HTTP status codes. Choosing the right one helps you control how search engines and browsers interpret your changes. 1. 301 Permanent Redirect A 301 redirect tells browsers and search engines that the page has moved permanently. It’s the best option when you want to preserve SEO rankings and transfer link equity. <?php header("Location: https://example.com/new-page.php", true, 301); exit(); ?><?php header("Location: https://example.com/new-page.php", true, 301); exit(); ?> Use this when: You’ve changed your domain or site structure. You want search engines to update to the new URL. You’ve deleted a page but have a new one that replaces it. A 301 redirect keeps your SEO value intact and ensures users always reach the correct page. It’s the best long-term redirect for stable, permanent changes. 2. 302 Temporary Redirect A 302 redirect signals that the move is temporary. Use it when a page is under maintenance or during A/B testing. <?php header("Location: https://example.com/temporary-page.php", true, 302); exit(); ?><?php header("Location: https://example.com/temporary-page.php", true, 302); exit(); ?> Search engines won’t replace the old URL in their index with a 302, which makes it safer for short-term changes. When your page returns to its original address, a 302 redirect ensures no SEO data is lost. It’s the ideal choice for brief or experimental updates. PHP Redirect Without Changing the URL Sometimes you need to display content from another domain while keeping your own URL in the address bar. This setup is common when combining content from different sources or showing third-party pages under your brand’s domain. However, it should be used with caution due to SEO implications. Here’s a simple example using PHP’s readfile() function: <?php $url = 'https://example.com/new-page.php'; echo file_get_contents($url); ?><?php $url = 'https://example.com/new-page.php'; echo file_get_contents($url); ?> This method displays the remote content without redirecting the browser. However, it’s not recommended for large or dynamic sites, it increases server load and can create SEO duplication issues. For SEO-safe domain proxies, use .htaccess rules with the [P] flag, as described in Redirect a Domain Without Changing the URL. When possible, use proper 301 redirects instead of masking URLs. This maintains SEO integrity and ensures consistent visitor tracking. Redirect After a Form Submission Redirecting after a form submission helps guide users to confirmation pages or new actions. It also prevents duplicate submissions if someone refreshes the page. This method is widely used in contact forms, signup pages, and checkout flows. <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // process form data here header("Location: thank-you.php"); exit(); } ?><?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // process form data here header("Location: thank-you.php"); exit(); } ?> This prevents duplicate submissions when users refresh the page and creates a smooth post-submission experience. Adding redirects after form processing improves usability and makes your site feel more professional. It’s also a simple way to track conversions or completed actions. Redirect Based on User Type or Session Conditional redirects let you send visitors to different locations depending on who they are or what they’re doing. This is useful for login systems, membership sites, or marketing campaigns with personalized landing pages. You can easily achieve this using PHP’s session management. <?php session_start(); if (!isset($_SESSION['user_id'])) { header("Location: /login.php"); exit(); } else { header("Location: /dashboard.php"); exit(); } ?><?php session_start(); if (!isset($_SESSION['user_id'])) { header("Location: /login.php"); exit(); } else { header("Location: /dashboard.php"); exit(); } ?> This code checks if a user is logged in. If not, they’re redirected to the login page; otherwise, they’re sent to their dashboard. Using conditional logic gives your redirects purpose and personalization. It also makes managing secure and role-based content more efficient. Redirect to HTTPS Automatically Redirecting users to HTTPS helps keep data secure and builds visitor trust. If your .htaccess rules aren’t applying properly, you can do it directly with PHP. This ensures all users access the secure version of your site. <?php if ($_SERVER["HTTPS"] != "on") { $redirect = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; header("Location: $redirect", true, 301); exit(); } ?><?php if ($_SERVER["HTTPS"] != "on") { $redirect = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; header("Location: $redirect", true, 301); exit(); } ?> However, for permanent SSL enforcement, the .htaccess or cPanel redirect method described in Forcing Visitors to Use Shared SSL is more efficient. This approach adds an extra layer of protection for websites without access to server-level redirects. It’s an easy fallback for ensuring HTTPS compliance across your site. Redirect Entire Folders or File Types in PHP Sometimes you need to redirect a group of pages at once, such as when you change file extensions or folder names. Instead of listing each URL manually, you can automate it using PHP. This approach works well during rebrands or site restructures. Redirect all .php files to .html equivalents: <?php $old_ext = ".php"; $new_ext = ".html"; $redirect = str_replace($old_ext, $new_ext, $_SERVER["REQUEST_URI"]); header("Location: $redirect", true, 301); exit(); ?><?php $old_ext = ".php"; $new_ext = ".html"; $redirect = str_replace($old_ext, $new_ext, $_SERVER["REQUEST_URI"]); header("Location: $redirect", true, 301); exit(); ?> This works like a dynamic mapping rule; it reads the original request and sends visitors to the updated file path. Bulk redirects save time and reduce the risk of broken links. They’re a smart way to handle large-scale content changes efficiently. Testing Your Redirects Testing verifies that your redirects send users to the right location with the correct status code. A simple check before publishing can prevent broken links and SEO issues. You can test using browser tools or command-line utilities. Using Browser Developer Tools Open the Network tab in Chrome or Firefox. Refresh the page you redirected. Look for the 301 or 302 response code. Using cURL (Command Line) Run this command: curl -I https://example.com/old-page.phpcurl -I https://example.com/old-page.php You should see output like: HTTP/1.1 301 Moved Permanently Location: https://example.com/new-page.phpHTTP/1.1 301 Moved Permanently Location: https://example.com/new-page.php If the status code doesn’t appear or shows 200 OK, check your syntax or confirm that the redirect code runs before any output. Always verify redirects before deployment. Doing so prevents loops, errors, and indexing issues later on. Troubleshooting Common Redirect Issues Redirect errors usually come from syntax mistakes or code placement. Fortunately, most are easy to identify and fix. Use this quick reference table when something doesn’t work as expected. ProblemCauseSolution“Headers already sent” errorMove the redirect code to the top of the fileMove the PHP block above the page outputInfinite redirect loopRedirect URL points back to itselfDouble-check the redirect destinationWrong redirect typeForgot the status code parameterAdd true, 301 or true, 302Redirect doesn’t triggerPHP code placed after HTMLMove the PHP block above the page outputBrowser caching old redirectThe browser stored the previous redirectClear cache or test in incognito mode These are some of the most frequent redirect problems developers encounter. With careful testing and placement, PHP redirects can run reliably and error-free. PHP Redirect vs. .htaccess Redirect When deciding how to manage redirects, it helps to know how PHP compares to .htaccess. Both can handle the same outcome but operate at different stages of the request process. This table shows when each method makes the most sense. FeaturePHP Redirect.htaccess RedirectRuns atApplication levelServer levelSpeedSlightly slowerFasterControlConditional and dynamicStatic and globalSyntaxPHP codeApache rewrite rulesBest forLogic-based redirectsSimple page/domain moves If you only need to move pages or enforce HTTPS, .htaccess rules like those in How to Set Up a 301 Redirect in .htaccess are the preferred option. PHP is best when you need decision-based logic. Understanding when to use each method helps keep your redirects organized and efficient. Mixing both approaches can provide the best balance of speed and flexibility. PHP Redirect Best Practices Following best practices ensures your redirects stay fast, predictable, and easy to maintain. These habits also help prevent SEO loss during major website changes. Keep these principles in mind when implementing your redirects. Always use exit() after redirect headers. Avoid mixing redirects and output in the same file. Use absolute URLs for clarity. Keep redirect logic in a separate configuration or include file. Test frequently and document every redirect. For SEO safety, use 301 redirects whenever a page or URL permanently changes. Reserve 302s for short-term use. Good redirect habits prevent headaches down the road and make future maintenance easier. Proper testing and documentation are the best insurance for site stability. Summary Redirects are a small but powerful part of website management. PHP provides a flexible way to control how users and search engines navigate between URLs. Whether you’re migrating pages, testing campaigns, or enforcing HTTPS, knowing how to use PHP redirects helps your site stay reliable and search-friendly. A PHP redirect lets you move users from one page or domain to another dynamically, using server-side code. For permanent changes, use 301 redirects; for temporary or testing purposes, use 302s. Test each redirect carefully, and if you need to handle bulk or complex cases, combine PHP redirects with .htaccess or cPanel tools. Using PHP redirects properly ensures a smooth, professional experience for your visitors. It also protects your SEO value and gives you fine-tuned control over your website’s flow. Share this Article Carrie Smaha Senior Manager Marketing Operations Carrie enjoys working on demand generation and product marketing projects that tap into multi-touch campaign design, technical SEO, content marketing, software design, and business operations. More Articles by Carrie Related Articles How To Create a PHP Redirect (301, 302, and Dynamic Redirect Examples)