Rewrite URL condition - Change particular string &

2019-08-18 15:13发布

问题:

What's the best way to rewrite URLs as 301 redirects with the following conditions?

Sample old URLs to rewrite:
/c/garments-apparel/red-yellow-polka-dress-10_450
/c/shoes-and-accessories/black-suede-boots-02_901

Conditions:

  1. Change c to category
  2. Remove trailing number (including connecting dash) from URL (example: -10_450 and -02_901)

New URLs should be:
/category/garments-apparel/red-yellow-polka-dress
/category/shoes-and-accessories/black-suede-boots

Note that changes will be applied to an .htaccess file on a Wordpress environment.

回答1:

You can have this rule just below RewriteEngine On line:

RewriteEngine On

RewriteRule ^c/([\w-]+/.+)-[\d_]+/?$ /category/$1 [L,NC,R=301]


回答2:

you can use the regex

[-_]\d+

to replace the trailing numbers with "" (empty string) demo

then use the regex

\/c\/

and replace with /category/ demo