Mod rewrite , much useful module in apache httpd web server. Although, we utilize it for rewriting the url , redirection, I just want to point out about a special flag which acts like a while loop by which you can achieve looping in mod rewrite rule
So let’s say, you have a requirement that you want to replace some character or want to process mod rewrite rule , just like a do while loop, but you do not have any control over, how many times it can appear in url.
So you want to replace each of the underscore by hyphen.
This is achieved by N [Next] flag in rewrite condition.
RewriteEngine on RewriteRule ^(.+)_(.+)$ $1-$2 [N]
question:- How to control, then number of loop iteration ?
RewriteEngine on RewriteRule ^(.+)_(.+)$ $1-$2 [N=10] #It means , iteration will be 10 times.
Imp-1 :- If you do not specify default looping is 32000 .
Imp-2 :- Controlling iteration in directory path as well.
Let’s say url is https://example.com/dir_1/dir_2/test_underscore_replace_by_hyphen
if you test this url against the above rule, it will not produce the desired result.
if you check error log , you will find the
“add path info postfix” line.
it means , mod_rewrite will iterate over request uri and search and it will add the path next to it. this will create a url that will not be valid.
Coming to point,
Add DPI [discardpath] flag
RewriteEngine on RewriteRule ^(.+)_(.+)$ $1-$2 [N,DPI] #It means , iteration will be 10 times. result will be https://example.com/dir-1/dir-2/test-underscore-replace-by-hyphen