Search code examples
.htaccessopencart

htaccess forward /merch/[all subfolders] to /en-gb/catalog/merch/[all subfolders


Apologies if this has been answered before. I'm sure it has but I can't find a proper solution anywhere.

I've (foolishly) upgraded from opencart 2 to opencart 4 and annoyingly it's adding /en-gb/catalog/ to the front of all categories and products. The site has had a load of seo done to it so I'm trying to forward the old addresses to the new ones.

There's only a handful of root categories so I figure if I can get everything within merchandise forwarded correctly then all the sub-folders of merchandise will also forward the same way and save me a TON of time.

So I'm trying to set up my .htaccess to forward one of the existing root categories, e.g.:

domain.com/merchandise/[all subfolders]

to

domain.com/en-gb/catalog/merchandise/[all subfolders]

Here's what I've got but it's not quite working

RewriteRule ^merchandise/(.*) /en-gb/catalog/merchandise/(.*) [R=301,NC,L]

What am I doing wrong and is there a way to do it right?


Solution

  • RewriteRule ^merchandise/(.*)$ /en-gb/catalog/merchandise/$1 [R=301,NC,L]
    

    This rule is "correct", the $1 backreference in the substitution string contains the URL-path captured from the subgroup in the RewriteRule pattern.

    The only additional points that could prevent this from working:

    1. This rule must go at the top of the .htaccess, before any existing rewrites (front-controller pattern). (If you placed this at the end of the file then it would only redirect static assets that might be contained in a merchandise subdirectory.)

    2. Make sure the browser (and any intermediary) caches are cleared. 301 (permanent) redirects are cached persistently by the browser so can make testing problematic (any "errors" are also cached). Test first with a 302 (temporary) redirect to avoid potential caching issues.

    Other minor points:

    1. The $ at the end of the RewriteRule pattern is redundant, since the regex .* is greedy by default.
    2. The NC flag is likely redundant unless you specifically need to match mixed case versions of merchandise?
    3. You could also include merchandise in the captured group and avoid repeating this in the substitution string (also lessens the chance of typos).

    For example, the following is effectively the same, but shorter:

    RewriteRule ^(merchandise/.*) /en-gb/catalog/$1 [R=301,L]