Years ago I saw Jeff Starr of Perishable Press set up shortlinks for a book of his where URLs such as example/u/123 redirected to example?p=123. I thought that was a handy way to set up no-hassle shortlinks using the WordPress post id.
I can't find the snippet back and I'm not good with htaccess. Here's a relevant snippet I found that I'm trying, but it's returning 404s. Is this on the right track, how would you fix it?
RewriteEngine On
RewriteRule ^go/(\d+)$ /?p=$1 [R=302,L]
Years ago I saw Jeff Starr of Perishable Press set up shortlinks for a book of his where URLs such as example/u/123 redirected to example?p=123. I thought that was a handy way to set up no-hassle shortlinks using the WordPress post id.
I can't find the snippet back and I'm not good with htaccess. Here's a relevant snippet I found that I'm trying, but it's returning 404s. Is this on the right track, how would you fix it?
RewriteEngine On
RewriteRule ^go/(\d+)$ /?p=$1 [R=302,L]
Share
Improve this question
asked Jul 10, 2019 at 19:19
nathanbwebnathanbweb
9251 gold badge7 silver badges5 bronze badges
1
|
1 Answer
Reset to default 2So 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 );
.htaccess
file. :p I've revised the answer and I hope it's still helpful... – Sally CJ Commented Jul 12, 2019 at 13:26