简体   繁体   English

mod_rewrite规则

[英]mod_rewrite rule

What rule translates urls like so? 什么规则会像这样翻译网址?

host.com/plastic_toys/pink_barbie/
host.com/index.php?q=plastic+toys+pink+barbie

The number of components in the category and product name vary. 类别和产品名称中的组件数量各不相同。

Edit: 编辑:

I guess this rule does part of the job: 我想这条规则可以完成部分工作:

RewriteRule ^([^/]*)/([^/]*)$ /index.php?q=$1+$2 [L]

The problem with the above rule is that it does not take care of converting underscores to + , so it translates like this: 上述规则的问题在于它不会将下划线转换为+ ,因此它会像这样翻译:

host.com/plastic_toys/pink_barbie/
host.com/index.php?q=plastic_toys+pink_barbie

I guess I have to delegate that conversion to PHP. 我想我必须将转换委托给PHP。 Now is there a way to test if the rule actually does the conversion the way I imagine it would? 现在有没有办法测试规则是否实际按照我的想象进行转换?

Is there a reason (existing code, etc) that you need to do this totally as a rewrite? 有没有理由(现有代码等)你需要完全重写这个?

Normally, I do 通常,我这样做

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

and then parse $_GET["q"] or even just parse $_SERVER["REQUEST_URI"] directly. 然后解析$_GET["q"]甚至直接解析$_SERVER["REQUEST_URI"] preg_match() is your friend here. preg_match()是你的朋友。

It takes way less time to use one of these two methods than it does trying to come up with a weird rewrite. 使用这两种方法中的一种方法比尝试进行奇怪的重写需要花费更少的时间。

First - I would suggest using the following rules: 首先 - 我建议使用以下规则:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z_]+)/([a-zA-Z_]+)/?$ /index.php?q1=$1&q2=$2 [L,QSA]

The RewriteCond each check that a valid file or directory does not exist (for instance if you want to have a static /help.html and it exists, or /FAQ/index.php and it exists then the RewriteRule will not fire. RewriteCond每次都检查一个有效的文件或目录是否存在(例如,如果你想要一个静态的/help.html并且它存在,或者/FAQ/index.php并且它存在,那么RewriteRule将不会触发。

I've split out the parameters into 2 items - so you can treat them as separate parameters (if you want to treat it as 1 parameter just change it to /index.php?q=$1-$2 or some other separator that you want - I would say do not use + since you want to parse off that character anyway). 我已将参数拆分为2个项目 - 因此您可以将它们视为单独的参数(如果您想将其视为1参数,只需将其更改为/index.php?q=$1-$2或您想要的其他分隔符) - 我会说不要使用+,因为你想解析那个角色无论如何)。

Nothing. 没有。 How would a rule know where to draw the line between a category and product. 规则如何知道在类别和产品之间划线的位置。 What if the query had 3 parameters. 如果查询有3个参数怎么办? Are the first two the category and the last the product or is the first the category and the last two the product. 前两个是产品类别,也是最后一个产品,或者是第一个产品类别和最后两个产品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM