Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I've seen this previous question on ServerFault, and I want something similar, but I'm not sure how to accomplish it.

What I want is to remove all slashes from the permalink except for the one that goes after the domain name. For example:

http://www.muycomputerpro.com/Actualidad/Especiales/La-Ciudad-Eficiente-Netapp

would be redirected to

http://www.muycomputerpro.com/ActualidadEspecialesLa-Ciudad-Eficiente-Netapp

I need it to correct some 404 errors remaining on my WordPress blog under Apache web server. So, what would be the right rewrite rule?

share|improve this question

1 Answer 1

Since RewriteRule starts with the path (so we don't need to worry about the domain), what you can say is that you want to remove all slashes except for the first one, or, remove a slash when not preceded by the start of string.

Which in regex means using a negative lookbehind, like this:

(?<!^)/

Where the (?<!...) is the negative lookbehind syntax and ^ means start of string.

So in the config it'll look like:

RewriteRule (?<!^)/ $1 [L,R=301]

One thing here which is a bit of a guess is the $1 to represent empty string - I've not done this with mod_rewrite before, and I couldn't find anything explaining if there is a "correct" way to replace with empty string, but in other regex engines, using an unused back reference will result in empty string, so should be fine. (If not, I'd see if "" worked instead.)

Oh, and the [...] part is a comma-delimited list of rewrite options. The L is for Last - saying don't process further rules (usually this is desired behaviour) and the R=301 is a 301 (permanent) redirect (instructing spiders to update their records with the new URL). More details on the rewrite options here.

share|improve this answer
    
It has worked Peter, but I didn't think about all the consequences: I've got some categories/subcategories in my blog (www.muycomputerpro/actualidad/noticias) and they are converted too (www.muycomputerpro/actualidadnoticias), and I'd prefer to maintain this hierarchy. I'm investigating other options, but great answer anyway! –  javipas Jan 5 '11 at 19:10
    
Depending on the details, you can add a negative lookahead too - e.g. (?<!^)/(?!noticias|and|others) to prevent slashes that are followed by "noticias" or "and" or "others" from being converted - obviously requires a bit of thought & planning on exactly what you want updated though. –  Peter Boughton Jan 7 '11 at 18:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.