Hi Hassan, and welcome to WebmasterWorld!
There's too much code there for anyone here to "do it for you," and that's not what this forum is about -- please see our
Forum Charter [webmasterworld.com].
However, we'll be glad to help you do it for yourself, if you can reduce the size of the initial problem, and tell us exactly what you think that problem is...
There is a lot of room to optimize this code, but really, it doesn't look too bad -- At least some of it should work OK.
So the question is, what problem are you having? How did you test this code, what were the results, and how did those results differ from what you expected?
To make this easier, here's what you appear to be wanting to do:
1) Change all
URLs linked from your pages to a static-looking format. You will do this by editing your static pages and by modifying your scripts that generate your dynamic pages (PHP preg_replace is handy for this).
2) Rewrite Web client requests for those new
URLs to the correct dynamic
filepaths inside your server. (This dynamic filepath is the same as before, and used to be part of your old URLs.)
Note the distinction between URLs and filepaths -- URLs are defined by the links on your pages, and URLs exist as soon as you publish them as links in your pages on the Web. The URLs you publish exist whether or not they resolve to any files on any servers.
Filepaths are defined and used inside your server. They exist only when you (or one of your scripts) create the directories and files.
I strongly suggest that you comment-out most of this code, start with just one or a few rules, and test only a few at a time. After a few of the rules are working, we can help you to reduce the size of this code to about a third of its present size, and likely speed it up even more than that.
Jim