.htaccess pretty url problem (mod_rewrite)

 ̄綄美尐妖づ 提交于 2019-12-25 03:15:47

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3138086/htaccess-pretty-url-problem-mod-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!