So I’m not sure why that RewriteRule
returned a 404 error for you, because I’ve tested it and it did work as expected — if permalinks are actually enabled, you would be redirected to the actual post permalink.
And here’s the content of my .htaccess
file:
RewriteEngine On
RewriteRule ^go/(\d+)$ /?p=$1 [R=302,L]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
I.e. I put the custom rewrite rule above the WordPress rewrite rules. That way, your custom rules would work and remain even when WordPress permalinks are updated.
Nonetheless, you could also use the parse_request
to achieve the same results (i.e. redirection):
add_action( 'parse_request', function( $wp ){
if ( preg_match( '#^go/(\d+)$#', $wp->request, $matches ) ) {
if ( $matches[1] && get_post( $matches[1] ) ) {
wp_redirect( get_permalink( $matches[1] ) );
exit;
}
}
}, 0 );