4

On my staging subdomain I want to make the canonical URL for each page the URL of the page on my main site. My CMS is WordPress.

I want to do this so that if Google crawls my staging site I won't risk pages on my main site losing rankings because of duplicate content.

Ex: on staging.example.com

<link rel="canonical" href="example.com/{the-page}" />

Canonical URLs on my website are being set with the Yoast SEO Wordpress Plugin.

How can I accomplish this?

6
  • I had one of my staging servers set up like this with canonical tags and after you asked your last question I thought I should check on it. It turns out Google was indexing thousands of pages from it despite the canonical tags. I went ahead and followed my own advice and password protected it. Aug 26, 2021 at 22:42
  • @StephenOstermiller I'm assuming that no-index was was set as well? Aug 26, 2021 at 22:55
  • Also @StephenOstermiller see my comment on my answer...should make you smile Aug 26, 2021 at 23:03
  • 1
    I didn't use noindex because I try to keep my staging server and my live site as much the same as possible. I try to avoid if (staging){... because I find it error-prone. That especially goes for things that aren't immediately obvious and visible such as meta tags. I was just using canonical tags because those tags would be identical on the staging and live servers with my domain name hardcoded in them. Aug 27, 2021 at 0:01
  • That makes sense, I 100% agree with avoiding that conditional - sound reasoning. But that also explains your indexation issue. As we know canonical on its own is going to be a toss up but I respect the gamble. Do you still have that data? Would interesting to see indexed/not against GA acquisition metrics. Aug 27, 2021 at 2:00

1 Answer 1

3

In your WordPress site's functions.php add the following filter.

add_filter( 'wpseo_canonical', function( $canonical ) {
    return str_replace( 'staging.example.com', 'example.com', $canonical );
} );

This will catch the variable that Yoast sets for the canonical URL and swap out your staging domain for the primary domain.

This method will work across domains too, you can enter anything you like in replace of example.com but must be inside single quotes.

If you'd like a solution that supresses the Yoast SEO canonical, and and accomplishes this with a universal PHP solution see this answer.

1
  • 1
    Just realized my answer to this doesn't work properly because Yoast doesn't send canonical if the page is also set to no-index. Must set <link rel="canonical" href="https://example.com<?php echo $url=strtok($_SERVER["REQUEST_URI"],'?');?>"> per the other answer...which actually makes that a better solution...for now Aug 26, 2021 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.