Home > Net >  Rewrite Rule for 301 redirections structure
Rewrite Rule for 301 redirections structure

Time:03-17

I have developed a project where url structure has changed from the old webpage and I need to create 301 redirects to avoid SEO penalization. After reading a lot I can't find how to do this rewrites.

Old URL

/es/madrid/comprar/893134/prop-712/

New URL

/es/property/prop-712/

Idea approach

RewriteRule ^/$1/property/$5  /$1/$2/$3/$4/$5/

What I need is using only the first path as param (/es/) and the last (/prop-712/) to restructure the URL /$first/property/$second and remove the $2, $3 & $4.

As you will see we share the last param (prop-712) of the URL. Any idea if this is possible?

CodePudding user response:

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

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

This will redirect a URL of the form /<lang>/<one>/<two>/<three>/<prop>/ (trailing slash optional) to https://example.com/<lang>/property/<prop>/. Where <lang> is any two lowercase letter language code and example.com is your canonical hostname. This matches exactly 3 path segments in the middle that are removed.

The regex [\w-] matches each path segment, including the property (last path segment). This matches characters in the range a-z, A-Z, 0-9, _ (underscore) and - (hyphen).

Only the first and last path segments are captured and later referenced using the $1 and $2 backreferences respectively. The parenthesised subpattern in the middle (ie. (?:/[\w-] ){3}) that matches the 3 inner path segments is non-capturing (indicated by the (?: prefix).

You do not need to repeat the RewriteEngine directive, since this already occurs later in the file inside the WordPress code block.

Test first with a 302 (temporary) redirect to prevent potential caching issues. Only change to a 301 (permanent) redirect when you are sure it is working as intended.


A quick look at your "idea":

RewriteRule ^/$1/property/$5  /$1/$2/$3/$4/$5/

In .htaccess files, the URL-path that the RewriteRule pattern matches against, does not start with a slash.

Backreferences of the form $n are used to reference capturing groups in the RewriteRule pattern (first argument). Backreferences can only be used in the substitution string (second argument)*1. You can't use backreferences in the RewriteRule pattern itself (which is a standard regex) - the $ carries special meaning here as an end-of-string anchor (regex syntax).

(*1 ...and the TestString (first) argument of any preceding RewriteCond directives, but this does not apply here.)

Reference:

  • Related