2

I am sure theres a better way to do this, but cant really figure it out.

Can somebody tell me if theres a better way to write to following Apache .htaccess rewrite rules?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)$ /index.php?param1=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)$ /index.php?param1=$1&param2=$2 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ /index.php?param1=$1&param2=$2&param3=$3 [L,QSA]
Morten Larsen
  • 166
  • 1
  • 4
  • 1
    I would do this programmatically: `RewriteRule ^.*$ index.php?uri=$0 [QSA,L]` and then in your code I would explode on `/`. – HamZa Jan 04 '15 at 23:59
  • I don't see the recursion in your rule. At any time only 1 rule is executed. [This question](http://stackoverflow.com/questions/3655893/rewriting-an-arbitrary-number-of-path-segments-to-query-parameters#3683855) is sort-of related, but handles actual key-value pairs as opposed to only values, and also actually uses recursion to accomplish something. If these are your only rules, I think this solution is not too bad. – Sumurai8 Jan 06 '15 at 14:18

1 Answers1

0

If you just have 3 path segments your current code does not seem that bad. Your current rules are easy to understand, and I don't think the duplicated conditions !-f and !-d will have a huge performance impact.

You can rewrite your current rules to a sequence like this. First you rewrite the url val1/val2/val3/val4/val5 to index.php/val1/val2/val3/val4/val5. Then we have a bunch of similar rules that all take the first path segment and turn it into a parameter. Once no more path segments remain the rest of the rules are ignored.

#Only on requests with at least 1 character (e.g. not to http://localhost)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php%{REQUEST_URI} [QSA]

#Since we don't have the L flag, this will do param1 - paramx in one go
RewriteRule ^index\.php/([^/]+)(/.*)?$ index.php$2?param1=$1 [QSA]
RewriteRule ^index\.php/([^/]+)(/.*)?$ index.php$2?param2=$1 [QSA]
RewriteRule ^index\.php/([^/]+)(/.*)?$ index.php$2?param3=$1 [QSA]
RewriteRule ^index\.php/([^/]+)(/.*)?$ index.php$2?param4=$1 [QSA]
RewriteRule ^index\.php/([^/]+)(/.*)?$ index.php$2?param5=$1 [QSA]

Before using this, you should test both the performance of these rules and your current rules to see which one performs better. Please note that this approach yields strange results if more than, in this case, 5 path segments are in the url, as the 6-th until nth path segment will overwrite param1 - param5. You could 'fix' this by adding another rule RewriteRule ^index\.php index.php [END] on recent versions of Apache.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100