I have a magento web shop and i use a plugin to import stock, prices, products. Annoyingly this plugin doesnt save old urls if i update the product name etc. Is there a way i can do this with htaccess? For example, i removed the SKU from the end of a product URL but google has indexed some of these old URLs.
Is it possible to rewrite https://www.example.com/xerox-everyday-toner-for-tn242y-yellow-toner-cartridge-006r04226
to https://www.example.com/xerox-everyday-toner-for-tn242y-yellow-toner-cartridge
using some wildcards? Obviously everything before the word "cartridge" changes per product so i want a redirect that if a URL contains "-cartridge-" remove everything after that pattern as SKU lengths can change but only contain alphanumeric characters. If a URL does not contain "-cartridge-" do not do anything.
I've tried a few regex patterns using an online htaccess builder but i cant seem to get this correct (unless these sites dont process the regex and thats why i think they dont work).
CodePudding user response:
RewriteRule (. -cartridge)-. $ $1 [R=301,L]
This should do the job. Everything up to -cartridge
gets captured (capturing the dynamic part before and this static suffix in one go, means we don't have the assemble the substitution URL out of multiple parts, but can just use $1
), and after it a -
plus some arbitrary characters must follow.
is there anyway you can add a rule so it excludes if "multipack" comes after the "-cartridge-".
The often easiest way to do this, is to place a "do nothing" rule before the one that does the rewriting. Then you can work with a positive match ("if URL ends in -cartridge-multipack
, do nothing"), instead of trying to find a negated pattern.
RewriteRule -cartridge-multipack$ - [L]
RewriteRule (. -cartridge)-. $ $1 [R=301,L]
Pattern anchored at the end with $
(means nothing is allowed to come after this), -
for "no substitution", and the L
flag to make the rewrite engine stop the current round of processing.