2

I am trying to redirect some URLs using .htaccess but without any success. The problem is that I have to redirect two different parts of the URL.

Here is an example of what I have to redirect:

example.com/huawei-reparatie/huawei-mate-7-reparatie

has to be redirected to:

example.com/reparatie/huawei/huawei-mate-7

So what has to be done:

  • Split huawei-reparatie into reparatie/huawei
  • Remove the -reparatie at the end of every URL

These are dynamic URLs so it is not only this one. I have to redirect all these URLs for a lot of different brands (like huawei) and a lot of different devices (like huawei-mate-7)

I hope anyone can help me.

MrWhite
  • 11,643
  • 4
  • 25
  • 40
Mxkert
  • 121
  • 2
  • Does this answer your question? [Redirect, Change URLs or Redirect HTTP to HTTPS in Apache - Everything You Ever Wanted to Know About Mod\_Rewrite Rules but Were Afraid to Ask](https://serverfault.com/questions/214512/redirect-change-urls-or-redirect-http-to-https-in-apache-everything-you-ever) – Gerald Schneider Jan 29 '20 at 13:31
  • Thanks for your response. I did check it but I am not really seeing the solution for me. I think I know to little about rewrites to make any sense of that document. – Mxkert Jan 29 '20 at 13:38

1 Answers1

1

To clarify your requirements:

/first-second/text-to-keep-removethis

Should redirect to;

/second/first/text-to-keep

Where

  • first, second and removethis contain only lowercase a-z letters.
  • first and second are separated by a single hyphen.
  • removethis is prefixed by a single hyphen (which is also removed) and always occurs at the end of the URL-path.
  • text-to-keep is any series of a-z and hyphen characters.

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

RewriteEngine On

RewriteRule ^([a-z]+)-([a-z]+)/([a-z-]+?)-[a-z]+$ /$2/$1/$3 [R=302,L]

The RewriteRule pattern (first argument) is a regex that matches against the requested URL-path only, less the slash prefix.

The $n in the substitution string are backreferences to the corresponding capturing group (parenthesised subpattern) in the RewriteRule pattern.

Any query string present on the initial request will be passed through unaltered. If any query string should be removed then add the QSD flag (Query String Discard).

Note that this is a temporary (302) redirect. Only change to a 301 (permanent) redirect - if that is the intention - once you have confirmed this is working OK.

MrWhite
  • 11,643
  • 4
  • 25
  • 40