【问题标题】:mod_rewrite if you use an expression all over the place, can you put it in a "variable"?mod_rewrite 如果你到处使用一个表达式,你能把它放在一个“变量”中吗?
【发布时间】:2009-05-04 16:26:13
【问题描述】:

如果我在我的 htaccess 文件中使用以下 50 次:

重写规则 ^(bla|blo|bli|blu|bloi|bkdo|doid|boidi|woekj|dfpo8ds)/?$ /section_index.php?sectionurl=$1 [L]

那么是否可以将 bla|blo|bli|blu|bloi|bkdo|doid|boidi|woekj|dfpo8ds 放在变量中,而不是在每一行中再次使用它?如果是这样,我该怎么做?

【问题讨论】:

  • 您的问题到底是什么?请举例说明您认为变量如何解决您的问题。
  • 问题是我在 htaccess 文件中多次使用该 rewriterule 行。每次我必须再次编写整个 bla|blo|bli|blu|bloi|bkdo|doid|boidi|woekj|dfpo8ds 片断。所以我想把它放在一个变量中并开始这样做: RewriteRule ^(MVARIABLE)/?$ /section_index.php?sectionurl=$1 [L]
  • 但是为什么你在不止一个规则中使用相同的表达式呢?或者这个表达式只是另一个表达式的子表达式(可能是前缀)?同样,此类规则的示例会有所帮助。
  • 它只是一个子表达式。我这样使用它:^(MVARIABLE)/?$,下一条规则是 ^(MVARIABLE)/someotherstuffhere?$,下一条是 ^(MVARIABLE)/yetotherstuff?$ 等等...
  • 所以作为背景:该网站有一大堆以/bla/或/blo/等开头的url路径,然后它们是相同的,例如/bla/blogs/和/blo /blogs/,等等

标签: mod-rewrite


【解决方案1】:

你可以设置一个环境变量:

RewriteRule ^(bla|blo|bli|blu|bloi|bkdo|doid|boidi|woekj|dfpo8ds)/?$ /section_index.php?sectionurl=$1 [L,E=FOOBAR:$1]

现在可以使用%{ENV:FOOBAR} 访问该值。


编辑    另一种方法是分步处理请求并链接规则:

# first path segment
RewriteRule ^(bla|blo|bli|blu|bloi|bkdo|doid|boidi|woekj|dfpo8ds)/?([^/].*)?$ $2?sectionurl=$1 [QSA,C]
# second path segment
RewriteRule ^(blog|foo)/?([^/].*)?$ $2?arg1=$1 [QSA,C]
# third path segment
RewriteRule ^(bar|baz)/?([^/].*)?$ $2?arg2=$1 [QSA,C]
# last rule
RewriteRule ^$ section_index.php [L,QSA]

但是当你使用 PHP 时,你也可以使用 PHP 来解析请求路径,例如:

$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
$argNames = array('sectionurl', 'arg1', 'arg2', 'arg3');
foreach ($segments as $i => $segment) {
    if (isset($argNames[$i])) {
        $_GET[$argNames[$i]] = $segment;
    }
}
var_dump($_GET);

现在您只需使用此规则将每个请求发送到该 PHP 文件:

# exclude requests for existing files
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

【讨论】:

  • 这似乎不起作用,这就是我正在尝试的:RewriteRule ^(%{ENV:FOOBAR})/?$ /section_index.php?sectionurl=$1 [L]跨度>
  • 您不能在搜索模式中使用变量。但是您可以使用额外的RewriteCond,例如RewriteCond %{ENV:FOOBAR}%{REQUEST_URI} ^(bla|blo|bli|blu|bloi|bkdo|doid|boidi|woekj|dfpo8ds)/\1。但这不是很优雅。
猜你喜欢
  • 2011-04-11
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多