Pierre
Pierre

Reputation: 13

RewriteRule : replace hyphens with plus signs

I just moved my website to a new permalink structure and need to do the following for some URLs.

I'd like to take the final "slug" after the number in /Annuaire-Artisan-106-creation-complete-de-salle-de-bains.htm

Replace hyphens to plus signs, and redirect to /travaux/new+slug+with+plus+signs without the final .htm.

...So

/Annuaire-Artisan-106-creation-complete-de-salle-de-bains.htm

becomes

/travaux/creation+complete+de+salle+de+bains

I currently have :

RewriteRule ^Annuaire-Artisan-([0-9]+)-(.*)-(.*).htm$ /Annuaire-Artisan-$1-$2+$3.htm [L,R,NE]

... that correctly transform the hyphens in the last part to plus signs :

/Annuaire-Artisan-106-creation+complete+de+salle+de+bains.htm

But I can't find the second RewriteRule to ignore the initial Annuaire-Artisan-106-and final .htm and rewrite to /travaux/creation+complete+de+salle+de+bains

Any help would be greatly appreciated :)

Upvotes: 1

Views: 158

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

First of all, don't use the R|redirect flag at this stage, because the client will issue a new request for each hyphen replaced. This is also true for search engines, which might be bad for ranking. Rather use the L flag alone, or maybe N|next giving

RewriteRule ^(Annuaire-Artisan-[0-9]+)-(.*)-(.*)\.htm$ /$1-$2+$3.htm [N=100,NE]

N=100 restricts the loop to at most 100 hyphens. You may adjust this to less, if you like.

The following rule would then remove .htm and replace the leading part. It takes a similar pattern and now, it will redirect the client to the new URL

RewriteRule ^Annuaire-Artisan-[0-9]+-(.*)\.htm$ /travaux/$1 [R,L,NE]

When everything works as it should, you may replace R with R=301 (permanent redirect). Never test with R=301.

Upvotes: 1

Related Questions