Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to get a specific .htaccess rewrite done, but my regex skills are limiting me to do so;

example 1: should become

example 2: should also become

example 3: should also become

And so on. As I do not know on forehand what dir2, dir3, dir4, and so on will be, regex probably should be used. Also, I do not know on forehand how deep the directories will go (if there will be a dir3, dir4 or even dir5 at all). Urlencoded slashes also should be recognized. Using php to handle this is not an option.

Any help would be GREATLY appreciated!

share|improve this question
But you know dir1? – 0xC0000022L Feb 15 '13 at 16:17
Yes, dir1 is known – Tijmen Feb 21 '13 at 12:25
up vote 0 down vote accepted

To strip the third and subsequent directories:

RewriteRule ^/(dir1)/([^/]+)/(.+)/([^/]+)$ $1/$2/$4 [L]
share|improve this answer
Not just the last directory, as I do not know how many dirs there will be passed. So I want to strip all directories but the first 2 and the filename. So in my examples only the dir3/ (example 1) and dir3/dir4/ (example 2) parts should be stripped. Hopefully you can help me further – Tijmen Feb 21 '13 at 12:28
@Tijmen See my edit. – mgorven Feb 21 '13 at 16:38
Thanks again for your help, I'm almost there now. Your solution works, however because it needs the 3rd dir (and this is optional), I've added a 2nd rewriterule now to catch the urls without a 3rd dir. What still is a problem that the third and subsequent dirs might be separated by an urlencoded slash (%2F) instead of /. I'm still figuring out a solution for that. – Tijmen Feb 24 '13 at 15:42
@Tijmen Please add an example of this to your question. – mgorven Feb 25 '13 at 16:37
Example 3 added. – Tijmen Feb 25 '13 at 17:46

Your Answer


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.