2

What I am asking is very basic and I think it should work but I do not know why it doesn't.

Basically, I need these urls(1) to 301 redirect to these others(2)

  • (1) /es/madrid/ => (2) /es/madrid-es/
  • (1) /es/ibiza/ => (2) /es/ibiza-es/

This is my approach:

RewriteRule ^/es/madrid/ https://example.com/es/madrid-es/ [R=301,L]
RewriteRule ^/es/ibiza/ https://example.com/es/ibiza-es/ [R=301,L]
MrWhite
  • 43,179
  • 8
  • 60
  • 84
Eduhud
  • 208
  • 1
  • 10

1 Answers1

2
RewriteRule ^/es/madrid/ https://example.com/es/madrid-es/ [R=301,L]
RewriteRule ^/es/ibiza/ https://example.com/es/ibiza-es/ [R=301,L]

In .htaccess files, the URL-path that the RewriteRule pattern matches against, does not start with a slash. So the above directives will never match the requested URL, so won't do anything.

In other words, do it like this instead:

RewriteRule ^es/madrid/ https://example.com/es/madrid-es/ [R=301,L]
RewriteRule ^es/ibiza/ https://example.com/es/ibiza-es/ [R=301,L]

Note that these rules redirect /es/madrid/<anything> - is that the intention? Otheriwse, to match the exactly URL-path only then include an end-of-string anchor. eg. ^es/madrid/$.


However, you could combine these two rules. For example:

RewriteRule ^(es)/(madrid|ibiza)/ https://example.com/$1/$2-$1/ [R=301,L]

Where the $1 and $2 backreferences correspond to the captured groups (parenthesised subpatterns) in the preceding RewriteRule pattern.


Aside: And taking this a step further for any two character language code and place you could do something like this:

RewriteRule ^([a-z]{2})/(\w+)/ https://example.com/$1/$2-$1/ [R=301,L]

This would redirect /<lang>/<place>/<anything> to /<lang>/<place>-<lang>/ where <lang> is any two character language code.

MrWhite
  • 43,179
  • 8
  • 60
  • 84
  • 1
    Thanks again MrWhite! The rules you gave me `RewriteRule ^([a-z]{2})/(\w+)/ https://example.com/$1/$2-$1/ [R=301,L]` dont apply to my case as it happens only with these two pages. – Eduhud Mar 17 '22 at 09:30
  • @Eduhud Yes, that rule was rather generic (just serves as an example). However, you could combine just those two rules into one (as an academic exercise if nothing else). I've updated my answer. – MrWhite Mar 17 '22 at 09:39