最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I do a redirect to WordPress permalink with post id via htaccess?

programmeradmin0浏览0评论

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 Sorry about the previous answer. What I said about the 404 is true.. except, I didn't realize I hadn't actually saved the updated .htaccess file. :p I've revised the answer and I hope it's still helpful... – Sally CJ Commented Jul 12, 2019 at 13:26
Add a comment  | 

1 Answer 1

Reset to default 2

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 );
发布评论

评论列表(0)

  1. 暂无评论