(Apache Mod_Rewrite) Please help condense my request

I am trying to write a mod_rewrite rule set to fulfill the following conditions:

1) /aaa (redirects to) --> /xxx_aaa.php 2) /aaa/ --> /xxx_aaa.php 3) /aaa?w=x&y=z --> /xxx_aaa.php?w=x&y=z 3) /aaa/?y=z --> /xxx_aaa.php?y=z 4) /aaa/bbb/ --> /xxx_aaa_bbb.php 5) /aaa/bbb/ccc/ --> /xxx_aaa_bbb_ccc.php 6) /aaa/bbb/cc12-34cc --> /xxx_aaa_bbb_cc12-34cc.php 7) /aaa/bbb/ccc/?y=z --> /xxx_aaa_bbb_ccc?y=z.php 

The list above is not exhaustive, but it gives you an idea of ​​all the possible permutations that I am going to cover. Namely:

1) Up to three levels of subdirectory
2) Does the present slash closure work or not 3) Skip the GET request lines, if any

This is what I'm using at the moment:

 Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteRule ^([0-9a-zA-Z\-]+)$ /xxx_$1.php [L] RewriteRule ^([0-9a-zA-Z\-]+)/$ /xxx_$1.php [L] RewriteRule ^([0-9a-zA-Z\-]+)/\?([0-9a-zA-Z\-=&]+)$ /xxx_$1.php?$2 [L] RewriteRule ^([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)$ /xxx_$1_$2.php [L] RewriteRule ^([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/$ /xxx_$1_$2.php [L] RewriteRule ^([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/\?([0-9a-zA-Z\-=&]+)$ /xxx_$1_$2.php?$3 [L] RewriteRule ^([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)$ /xxx_$1_$2_$3.php [L] RewriteRule ^([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/$ /xxx_$1_$2_$3.php [L] RewriteRule ^([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/\?([0-9a-zA-Z\-=&]+)$ /xxx_$1_$2_$3.php?$4 [L] 

And it works fine.

But I can't help but think that there should be a much more elegant way to do this - perhaps even to reduce all of the above into one line.

Any ideas? Any help is much appreciated, thanks. :)

+4
source share
1 answer

Like this:

 Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteRule ^([0-9A-Z\-]+)/?$ /xxx_$1.php [L,QSA,NC] RewriteRule ^([0-9A-Z\-]+)/([0-9A-Z\-]+)/?$ /xxx_$1_$2.php [L,QSA,NC] RewriteRule ^([0-9A-Z\-]+)/([0-9A-Z\-]+)/([0-9A-Z\-]+)/?$ /xxx_$1_$2_$3.php [L,QSA,NC] 

NC = non case, therefore AZ = az

QSA = query string append =? w = x & y = z will be set (for example, $ _GET ['w'] in PHP)

+6
source

Source: https://habr.com/ru/post/1379783/


All Articles