Reputation: 441
I am trying to write a set of mod_rewrite rules 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 above list isn't exhaustive, but it gives you an idea of all the possible permutations I am aiming to cover. Namely, these are:
1) Up to three subdirectory levels
2) Works whether closing forward slash is present or not
3) Pass GET query strings, if present
This is that I use 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 seems to work just fine.
But I can't help but think that there must be a much more elegant way of doing it - perhaps even condensing all the above into one single line.
Any ideas? Any help much appreciated, thanks. :)
Upvotes: 4
Views: 842
Reputation: 49887
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 so A-Z = a-z
QSA = query string append = ?w=x&y=z will be set (for example $_GET['w'] in PHP)
Upvotes: 6