简体   繁体   English

Url重写没有固定的结构

[英]Url-rewrite with no fixed structure

i have this 3 url type: 我有这3个网址类型:

  • site.com/page site.com/page
  • site.com/page/action site.com/page/action
  • site.com/page/action?params site.com/page/action?params

the "page" is always here, but the 2 more is't “页面”总是在这里,但另外两个不是

how can make it work in this way every time? 怎样才能让它每次都以这种方式运作?

RewriteRule ^(.*)/(.*)?(.*)$ $1.php?action=$2&$3

Whith this one, if the last 2 parts is't here, stop working... 对于这个,如果最后两个部分不在这里,停止工作......

Thanks! 谢谢!

RewriteRule ^(.*)/(.*)$ $1.php?action=$2 [QSA,L]
RewriteRule ^(.*)$ $1.php [QSA,L]

You will want more than one rule for this (you could do it with one but readability-wise, 2 would be better. 你需要不止一个规则(你可以用一个但是可读性,2个会更好。

Firstly, forget about the query string. 首先,忘记查询字符串。 You aren't manipulating it, and the [QSA] flag can do the work of appending it to the resulting URL. 您没有操纵它, [QSA]标志可以将其附加到生成的URL。

You now need two rules, one to deal with the "action" variant, and one to deal with the page name only: 您现在需要两个规则,一个用于处理“action”变体,另一个用于处理页面名称:

RewriteRule ^[^/]+$ $0.php [L]
RewriteRule ^([^/]+)/([^/]+) $1.php?action=$2 [L,QSA]

However , this will cause a rewrite loop. 但是 ,这将导致重写循环。 The way that mod_rewrite works means that the rules will almost always be executed at least twice, and on the second (and all subsequent) iteration the first rule will match the rewritten URL. mod_rewrite的工作方式意味着规则几乎总是至少执行两次,而在第二次(以及所有后续)迭代中,第一条规则将匹配重写的URL。

So we need to be a little more specific: 所以我们需要更具体一点:

RewriteRule ^(?:(?!\.php$)[^/])+$ $0.php [L]
RewriteRule ^([^/]+)/([^/]+)$ $1.php?action=$2 [L,QSA]

This lookahead will ensure that the first rule only matches URIs that don't end with .php . 此前瞻将确保第一个规则仅匹配不以.php结尾的URI。

Note that the QSA flag is only applied to the second rule. 请注意, QSA标志仅适用于第二个规则。 This is because it only has an effect when the rewritten URI alters the query string - the default behaviour (when the query string is not altered) is to append the original query string. 这是因为它只在重写的URI改变查询字符串时才有效 - 默认行为(当查询字符串未被更改时)是附加原始查询字符串。

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

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