• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
NameHero Blog

NameHero Blog

Web Hosting Tips & Resources From NameHero

  • Web Hosting
  • Reseller Hosting
  • Managed Cloud
  • Domains
  • Account
  • Blog Home
  • Categories

How To Redirect A Page In WordPress Without A Plugin

Bhagwad Park

Published on: June 13, 2018

Categories: Showcase, WordPress 26

Let’s say you’re checking out your Google search console statistics and you find that some users have clicked through to a non-existent page on your site like this:

Redirect a Page in WordPress - 404 Errors

Oh no! A bad user experience means an immediate bounce back to the search results, and a possible signal to Google that your site isn’t giving users what they want.

The problem is that those pages don’t even exist on your site! Or they used to exist at one point, but not anymore. Google unfortunately didn’t get the memo and still sends visitors to your non-existent page. What do we do about it? The best thing is to use a 301 redirect to send users to another page that gives them what they’re looking for. If it doesn’t exist, create it! Obviously that page is doing something right by getting clicks in the SERPS. You need to capitalize on it.

Normally, this involves installing a plugin to redirect a page in WordPress. While that’s not a bad idea, it’s a bit excessive if you just want to redirect one or two pages. In this tutorial, I’ll show you how to accomplish this without a plugin. Either using your functions.php file in your themes directory, or via a PHP code insertor.

So let’s get started.

Step 1: Get the “From” URL Slug and the “To” URL Slug

Before we get into the code, you need to specifically write down two things:

  1. Which URL needs to be redirected
  2. To which URL should the users go to?

There are a few stumbling blocks here. First, check and see whether URLs on your site end with a “trailing slash” or not. In other words, are you this:

example.com/test-page

or this:

example.com/test-page/

To redirect a page in WordPress, we’re going to be matching strings in code. It’s extremely important to know exactly how your URLs are written.

Once you have the URLs, create the URL slugs. The “slug” is that part of the URL without the domain name, or https (or http).

So for the above example, the slug will be:

/test-page

Similarly if your URL is;

https://www.example.com/05/18/some-page

The slug will be:

/05/18/some-page

Note the initial slash “/” in front of the slug. This is going to be important.

Why Use Slugs and Not URLs?

In case you’re wondering why we don’t do a simple URL matching, the reason is simple. We want to insulate ourselves from potential changes. Maybe you create a subdomain for a page, or move your blog into a directory. Perhaps you’re using the HTTP protocol and one day want to move to HTTPS.

Without the slug, all your attempts to match the URL will fail because the initial part is changing. But the slug is eternal. The slug is forever!

Step 2: Code in functions.php to Redirect a Page in WordPress

The second step is to open your “functions.php” file located in your theme (preferably a child theme). Now paste the following code into it:

function redirect_page() {

     if (isset($_SERVER['HTTPS']) &&
        ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
        $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $protocol = 'https://';
        }
        else {
        $protocol = 'http://';
    }

    $currenturl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $currenturl_relative = wp_make_link_relative($currenturl);

    switch ($currenturl_relative) {
    
        case '[from slug]':
            $urlto = home_url('[to slug]');
            break;
        
        default:
            return;
    
    }
    
    if ($currenturl != $urlto)
        exit( wp_redirect( $urlto ) );


}
add_action( 'template_redirect', 'redirect_page' );

In this code, there are two sections in bold. Namely this one:

case '[from slug]':
    $urlto = home_url('[to slug]' );
    break;

This is where you enter your “from” and “to” slugs. Replace the sections in bold including the square brackets with the slugs you got from Step 1.

Save your changes, and now when you visit the “from” page, you should be redirected to the “to” page.

Step 3: Add More Redirects

I’ve structured the code in such a way that you can easily add more redirections if you want. For each new redirection, just place a new section like this under the first one:

case '[from slug]':
    $urlto = home_url('[to slug]' );
    break;

case '[from slug2]':
    $urlto = home_url('[to slug2]' );
    break;

Just make sure you keep the line “default” after all these “case” blocks and you should be fine. You can now redirect as many pages as you want to other pages without using a WordPress plugin!

Bhagwad Park Profile Picture
Bhagwad Park

I’m a NameHero team member, and an expert on WordPress and web hosting. I’ve been in this industry since 2008. I’ve also developed apps on Android and have written extensive tutorials on managing Linux servers. You can contact me on my website WP-Tweaks.com!

Reader Interactions

Comments

  1. Milena says

    December 17, 2018 at 5:41 pm

    Hello!
    Thank you so very much for putting this tutorial together. I just completed several redirects using your code and it worked out, very easy to follow.
    I wanted to comment on two things.

    I noticed a tiny typo within the post – regarding this specific string of code:
    case ‘[from slug]’:
    $urlto = home_url(‘[to slug]’);
    break;
    the correct code you first list works. Where you begin to explain adding it again to execute another redirect and so on the ‘ is missing from within the slug syntax.
    It says case ‘[from slug]: instead of case ‘[from slug]’:

    It wasn’t a problem at all to spot the typo and figure it out even though I am an utter novice. But I thought I’d mention it in case someone else has a difficulty.

    Thanks again for the helpful instructions.

    My second comment – once I added the code for the redirects all of my pages and posts, including the main blog page are now showing their slug at the top left of the screen prior to the H1. Would you happen to know why this happened and how I could remove the slugs from displaying?

    Reply
    • Bhagwad Park says

      December 19, 2018 at 10:36 am

      Hi Milena, thanks for spotting the errors! I’ve fixed the code now and it should work without the slug.

      I’d used the slug earlier as a debugging tool and forgot to remove it from the final output. Thanks again!

      Reply
  2. David says

    February 9, 2019 at 9:39 am

    Hi,
    This is great stuff. I have a question. I have two links on my site . Each link when clicked on would go to the custom login page. For eg. link 1 when clicked , would go to the custom login page. From there to the link1 url.

    Similarly for link2. Any help in this scenario would be appreciated.

    Thanks
    David

    Reply
  3. Nanna says

    March 8, 2019 at 1:50 am

    Hi,

    I keep getting different errors when I try to add the code in the functions.php.
    There is already over 600 lines of code in my file and I added it at the end – is that the mistake?
    If so, can you tell me where in the file I should add the code?

    Reply
  4. Torry says

    March 27, 2019 at 8:51 am

    Great article, I feel that I am on my way to solving my issue, so thanks for that.

    What if I want to redirect all pages that do NOT have a specific slug to the page that does have that slug? I’m looking for a way to automatically disable and redirect closed offers/signup pages to the current, in-use one, without having to find and modify each expired funnel page individually. I feel I could do it with a modification of this method, does that sound possible and what would you suggest?

    Reply
  5. Chris says

    May 31, 2019 at 7:07 am

    Great! But i want to redirect example.com/2/ to example.com/new/2/
    And i want it to be done in a way that i will not need to add 2, 3, 4, 5, 6 and so on for each page, this is a pagination function and i dont want to write a code for each new page that will be paginated, so i want one simple code that will take care of redirecting example.com/2/ to example.com/new/2/

    example.com/3/ to example.com/new/3/

    example.com/4/ to example.com/new/4/
    But i wont be adding new redirection with new page numbers.
    Am looking at example.com/*. / to redirect to example.com/new/$1 outputs the new numbers here.
    Please help me with such code, thanks.

    Reply
  6. Bishal Adhikari says

    July 11, 2019 at 1:59 am

    Following code is not working, is there some error ?

    function redirect_page() {

    if (isset($_SERVER[‘HTTPS’]) &&
    ($_SERVER[‘HTTPS’] == ‘on’ || $_SERVER[‘HTTPS’] == 1) ||
    isset($_SERVER[‘HTTP_X_FORWARDED_PROTO’]) &&
    $_SERVER[‘HTTP_X_FORWARDED_PROTO’] == ‘https’) {
    $protocol = ‘https://’;
    }
    else {
    $protocol = ‘http://’;
    }

    $currenturl = $protocol . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’];
    $currenturl_relative = wp_make_link_relative($currenturl);

    switch ($currenturl_relative) {

    case ‘[/news_board]’:
    $urlto = home_url(‘[/news-board]’);
    break;

    default:
    return;

    }

    if ($currenturl != $urlto)
    exit( wp_redirect( $urlto ) );

    }
    add_action( ‘template_redirect’, ‘redirect_page’ );

    Reply
  7. Roman says

    January 19, 2020 at 6:33 am

    Muchas gracias. Tu artículo me ha resultado muy útil y he podido resolver un problema de redireccionamiento. Saludos.

    Reply
  8. Rikaz Sheriff says

    February 15, 2020 at 12:57 am

    It never ceases to amaze me the resourcefulness of the internet. Thanks for this very useful piece of well written code! Work well.

    Reply
  9. Don says

    February 21, 2020 at 2:39 pm

    Trying to redirect my home page to another url, buy my homepage ends with .com, NO fwd slash or anything else. TY

    Reply
  10. Massimiliano says

    March 28, 2020 at 5:27 am

    Hi Bhagwad!
    Thanks for your tutorial.
    I’ve tried it for some tests, but on mobile it applies a different rule.

    On desktop:
    from /my-old-url/page
    to /my-new-url

    On mobile:
    from /my-old-url/page
    to /my-new-url/my-old-url/page

    Reply
  11. Law P says

    April 23, 2020 at 4:19 am

    Followed the procedure but still not working!

    Reply
  12. Carolynne says

    June 18, 2020 at 3:26 pm

    This sounds awesome. Is there a way I could redirect on certain days only? I only want to redirect On saturdays-Tuesday’s. Is this a possibility? Any help would be great. Thanks.

    Reply
  13. Buesi says

    July 19, 2020 at 4:54 pm

    Thank you so much!!! Works perfectly!! (had to do it in the function.php file of the child theme directly, because in wordpress it wouldn’t let me change the file for some reason)

    Reply
  14. Kenan says

    November 13, 2020 at 9:36 pm

    Thanks my friend. Excellent !

    Reply
  15. Olivia says

    November 17, 2020 at 9:19 am

    Really Thanks alot. Redirecting pages without plugins is awesome.

    Reply
  16. Vladimir Eric says

    November 19, 2020 at 7:53 am

    People like you convert WP users into developers. This trick is so effective and yet simple – saving the installation from one-more-not-necessary plugin.

    THANKS

    Reply
  17. Chen Lee says

    December 31, 2020 at 6:31 pm

    How can the code be modified to perform a 301 redirect?

    I am currently using your code and it is working well to perform a 302 redirect.

    Much appreciated!

    Reply
  18. Chen Lee says

    January 1, 2021 at 1:49 am

    I have modified one line of your code to do indicate it is a 301 redirect as follows

    original code exit( wp_redirect( $urlto ) );
    new code exit( wp_redirect( $urlto, 301 ) );

    it appears to be working on my site. Perhaps you can check and comment.
    Thank you.

    Reply
  19. Dimitar Georgiev - Biko says

    January 11, 2021 at 3:45 am

    I think it will be a lot more difficult to maintain those redirects on a bigger WP site with hundreds of redirects (including the old redirects to prevent redirect chains). Maybe it will be good idea to improve the post with some wildcard redirects too. Interesting theme indeed.

    Reply
  20. Thomas Clayson says

    April 18, 2021 at 7:56 am

    Absolutely 100% works. Thanks for sharing.

    Reply
  21. Vishal Dorge says

    May 18, 2021 at 10:37 am

    As a new blogger, I am working with a cheap shared hosting and can’t afford to install so many plugins… It worked, thanks.

    Reply
  22. Al says

    May 27, 2021 at 12:26 pm

    Perfect, thanks Chen.

    Reply
  23. Krasimir says

    August 13, 2021 at 12:15 pm

    Considering to move all redirects this way. Minus one plugin is always the better solution

    Reply
  24. eyal says

    February 13, 2022 at 7:03 pm

    Hi Bhagwad!
    Thanks for your tutorial.
    I have a new subdomain, replacing existing one due to some reasons.
    I have two pages with the same slug. The only difference is the subdomain name.
    one looks like this: m.site.com/x-y-z while the other looks like: mn.site.com/x-y-z
    I was trying to copy emtire urls, but it didn’t work.
    Any idea what to do?

    Reply
  25. Steve says

    July 20, 2022 at 2:42 am

    I want to redirect just like the old “Refresh” in html header but after 30 seconds not imediately and refresh to a different page

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow & Subscribe

Exclusive promos, content and more!

Most Popular Posts

NameHero’s Recommended WordPress Plugin and Theme Setup (2023)

How To Increase The InnoDB Buffer Pool Size

How To Fix A Stuck All-in-One WP Migration Import

How To Add A Subdomain In Cloudflare

How To Inline And Defer CSS On WordPress Without Plugins

Top Categories

  • WordPress
  • Website Performance
  • Web Hosting
  • Resellers
  • Website Security
  • VPS Hosting
  • Website Development
  • SEO Tips
  • Announcements
  • Domain Registration
NameHero

NameHero proudly provides web hosting to over 40,000 customers with 99.9% uptime to over 750,000 websites.

  • Master Card
  • Visa
  • American Express
  • Discover
  • Paypal
Name Hero
  • Web Hosting
  • Reseller Hosting
  • Managed Cloud
  • Domains
Help & Support
  • NameHero Blog
  • Knowledgebase
  • Announcements
  • Affiliates
Company
  • About Us
  • Contact Sales
  • Reviews
  • Uptime
  • We're Hiring

Copyright © 2023 NameHero, LLC. All rights reserved.

  • Privacy Policy
  • Terms of Use
  • Acceptable Use Policy
  • Payment Policy
  • DMCA