.htaccess pretty url problem (mod_rewrite)
I have a directory that lists products by categories. if a _GET
variable exists, it is used in a query. I would like to use "pretty url's", like: example/a/1/b/2/c/3/d/4
becomes example/index.html?a=1&b=2&c=3&d=4
most .htaccess
examples I see only use variables to replace the _GET
values, but I can use rules like this:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ index.html?$1=$2&$3=$4&$5=$6 [L]
RewriteRule ([^/]+)/([^/]+)/([^/]+)/([^/]+)$ index.html?$1=$2&$3=$4 [L]开发者_运维问答
RewriteRule ([^/]+)/([^/]+)$ index.html?$1=$2 [L]
And it works... However, the when I add longer and longer RewriteRules
(like out to &17=$18
), it stops working. The last variables in the chain turn into some sort of array based on earlier values (in above it would build index.html?a0=a1&a3=a4
)...
- Is there a better way to do this?
- It seems inefficient?
- Is there a limit to the number of variables in
.htaccess
- How long a rule can be?
Thanks!
mod_rewrite only supports up to $9
and %9
.
I recommend you either modify your script to use $_SERVER['PATH_INFO']
, or you use RewriteMap
to invoke a script to transform the path into a querystring.
mod_rewrite
only allows for you to have ten back-references, one of which is the whole matchable part (which ends up leaving you with only nine definable capture groups), so you're definitely limited by that.
However, to me it would make much more sense to examine the server's REQUEST_URI
/SCRIPT_NAME
/PATH_INFO
variable in your script file, and parse that to get the key-value pairs from the URL. Then, you'd simply have this in your .htaccess
:
RewriteRule On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.html [L]
And then your script would take care of the rest. I do have to wonder though, if you have that many GET
variables, is it actually more readable if they're all made into a "pretty" URL? After all, if you have twenty-some forward slashes in the URL, you may be equally well off just passing a normal query string at that point. It depends on your application though and how users interface with these URLs, so you may have good reason for wanting to do it this way.
精彩评论