【问题标题】:Apache2 htaccess multiple rulesApache2 htaccess 多条规则
【发布时间】:2014-11-09 04:39:31
【问题描述】:

我们已经为客户端构建了一个 Web 应用程序,它应该在调用某些特定 url 时显示。所有其他 url 应由现有的 Typo3 安装处理。不幸的是,我们无法访问 Apache2 配置,因此我无法访问重写日志或更改 VirtualHost 定义。

.htaccess 看起来大概是这样的:

RewriteEngine On

# http://example.com/sub/foo/
RewriteCond %{REQUEST_URI} ^/sub/foo/.*
RewriteRule .* special.php [L]

# http://example.com/sub/bar/year/2014/
RewriteCond %{REQUEST_URI} ^/sub/bar/.*
RewriteRule .* special.php [L]

# Everything else should be typo3
RewriteRule .* general.php [L]

但是,所有呼叫都被路由到general.php 文件。根据this page,.htaccess 应该按预期工作。服务器是 Apache 2.2。

有什么想法吗?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    您需要从最后一条规则中排除 special.php。规则 1 和规则 2 也可以像这样组合成一个:

    RewriteEngine On
    
    # http://example.com/sub/foo/
    RewriteRule ^sub/(foo|bar)/ special.php [L,NC]
    
    # Everything other than /special.php should be typo3
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule !^special\.php$ general.php [L,NC]
    

    更新 (Lars): 解决方案是了解 [L]-flag 的工作原理。它重新运行整个循环,因此每个重复出现的规则都必须以某种方式编写,它否定已经重写的部分。另外,从/sub/-目录中的.htaccess-文件来看,我放置了所有规则,第一个目录必须像这样省略:

    RewriteEngine On
    
    # http://example.com/sub/foo/
    RewriteRule ^(foo|bar)/ special.php [L,NC]
    
    # Everything other than /special.php should be typo3
    RewriteRule !^special\.php$ general.php [L,NC]
    

    【讨论】:

    • 这对我也不起作用 - general.php 总是被调用,无论使用什么 url。我也不明白,为什么在第二条规则上 url 应该被重写为 special.php - 如果第一条规则不匹配,为什么会这样?如果第一个规则匹配,则 [L] 标志应该停止第二个重写规则的每个被评估。
    • [L]-flag should stop the second rewrite rule from every being evaluated 这是很多人的误解。 L 标志仅强制 mod_rewrite 再次运行循环。所以第二次请求 uri 变为 special.php 并且最终也被重写为 general.php
    • 也试试我更新的规则。如果它不起作用,请提供它不起作用的 URL。
    • /sub/ 中没有任何 .htaccess 吗?
    • 不客气,很高兴你解决了这个问题。最好将RewriteBase /sub/ 保留在/sub/.htaccess 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2011-10-02
    • 2013-04-24
    • 2014-11-09
    • 1970-01-01
    相关资源
    最近更新 更多