简体   繁体   English

如何在.htaccess中自动化rewriterule?

[英]How to automatize rewriterule in .htaccess?

I'm doing this in .htaccess: 我在.htaccess中这样做:

RewriteRule ^([A-Za-z0-9-]+)[/]?$ /index.php?u1=$1 [L,QSA]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)[/]?$ /index.php?u1=$1&u2=$2 [L,QSA]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)[/]?$ /index.php?u1=$1&u2=$2&u3=$3 [L,QSA]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)[/]?$ /index.php?u1=$1&u2=$2&u3=$3&u4=$4 [L,QSA]

Is there any way to make this automatically from u1 to u(infinite), automatically, based on the length of the url, without having to define every case? 有没有办法根据网址的长度自动从u1到u(无限)自动生成,而不必定义每个案例?

No, neither Apache nor regex offer programmatic processing of an unspecified number of arguments. 不,Apache和正则表达式都不提供对未指定数量的参数的编程处理。 But PHP is designed for such things, so you're best off simply using one rule: 但是PHP就是为这样的东西而设计的,所以你最好只使用一个规则:

RewriteRule ^([A-Za-z0-9/-]+)$ /index.php?path=$1

Then have your PHP script break the path variable apart by calling the explode function on the forward-slash character. 然后通过调用forward-slash字符上的explode函数让你的PHP脚本分开path变量。 And you'll get an array containing each piece of the full path. 你会得到一个包含完整路径的每一段的数组。

This way your PHP script can handle an unlimited number of path elements, and Apache won't need to wear itself out trying to make sense of infinite regex patterns. 通过这种方式,您的PHP脚本可以处理无限数量的路径元素,并且Apache不需要自己试图理解无限正则表达式模式。

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

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