Search code examples
apache.htaccesshttp-redirect

Change and remove a part of url with redirect 301 (htaccess)


I converted a Joomla website to WordPress. Joomla article URLs have /blog/<RandomNumber>-slug. For example:

example.com/blog/164-postname

example.com/blog/214-anotherpostname

I need to remove /blog/164-postname from URL so it redirects to example.com/postname

Also there are some product category URLs with this format:

example.com/category/<RandomNumber>-slug

For example:

example.com/category/12-catname 

I want to redirect these urls by changing category to product-category and removing numbers and - character so mentioned URL redirects to example.com/product-category/catname with 301 code.


Solution

  • Try the following at the top of your root .htaccess file using mod_rewrite:

    # Redirect "/blog/123-postname" to "/postname"
    RewriteRule ^blog/\d+-([\w-]+)$ /$1 [R=301,L]
    
    # Redirect "/category/123-catname" to "/product-category/catname"
    RewriteRule ^(category)/\d+-([\w-]+)$ /product-$1/$2 [R=301,L]
    

    The $1 and $2 backreferences contain the match from the parenthesised subpatterns in the preceding RewriteRule pattern.

    Test first with 302 (temporary) redirect to avoid potential caching issues.