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'm trying to get a specific .htaccess rewrite done, but my regex skills are limiting me to do so;

example 1: www.domain.com/dir1/dir2/dir3/file.txt should become www.domain.com/dir1/dir2/file.txt

example 2: www.domain.com/dir1/dir2/dir3/dir4/file.txt should also become www.domain.com/dir1/dir2/file.txt

example 3: www.domain.com/dir1/dir2/dir3/dir4%2Ffile.txt should also become www.domain.com/dir1/dir2/file.txt

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
add comment

1 Answer

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
show 2 more comments

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.