Don’t use php header
function it will cause problems within wordpress.
WordPress has its own function to make redirects
Function Reference: wp_redirect($url, $status_code);
Try this:
<?php
$permalink = get_permalink( $id );
wp_redirect($permalink, 301);
exit;
?>
Updated:
I’ve worked out some code for you
Place this below code to your functions.php
file:
function redirector($post_id) {
if (is_single()) {
$redirect_to = get_permalink($post_id);
if (empty($_SERVER['HTTPS']))
$ht_prot="http://";
else
$ht_prot="https://";
$cur_link = $ht_prot . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$pattern = "https://wordpress.stackexchange.com/".$post_id.'\/+$/';
preg_match($pattern, $cur_link, $matches);
if(sizeof($matches) < 1) :
wp_redirect($redirect_to, 301);
exit;
endif;
}
}
And call this function to your single.php
file:
redirector($post->ID);
get_header(); ?>
Just before the get_header();
It will only redirect if you’re in single post.
You can further change this code as your needs.
Caution:
If later you wish to change the permalink structure please remove the function call because it will continuously redirect and cause an redirect error.