【问题标题】:Consolidating redundant RewriteCond lines in .htaccess在 .htaccess 中合并多余的 RewriteCond 行
【发布时间】:2014-07-29 10:16:03
【问题描述】:

我正在尝试合并 .htaccess 中的多个 RewriteCond 行,并且正在努力解决语法问题。这是我的.htaccess 文件的重定向区域的代码:

RewriteEngine On

# BEGIN page-level mobile redirects
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(index.html)?$ http://m.example.com [L,R=301]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^page-1/$ http://m.example.com/p1 [L,R=301]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^page-2/$ http://m.example.com/p2 [L,R=301]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^page-3/$ http://m.example.com/p3 [L,R=301]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^category/page-4/$ http://m.example.com/p4 [L,R=301]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^category/page-5/$ http://m.example.com/p5 [L,R=301]
</IfModule>
# END mobile redirects

上述解决方案工作正常,但效率低下,因为有太多冗余的 ReWriteCond 行。我的目标是让单个 RewriteCond 行应用于我的所有 RewriteRule 行。这可能吗?

我通常会使用REQUEST_URI 来更有效地完成此任务,但在这种情况下我无法这样做,因为我们正在重写对具有不同 URL 布局的多个类似桌面网站的请求,以单个移动网站文件夹。

【问题讨论】:

  • 我发布的解决方案做了它应该做的,但它效率低下,因为有很多冗余的 RewriteCond 行。我更新了我的 OP 以更清楚地说明我的要求。

标签: apache .htaccess mod-rewrite


【解决方案1】:

阅读 Apache 文档中的 skip 和 last 标志。您还可以使用正则表达式折叠一些行:

# BEGIN page-level mobile redirects
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_USER_AGENT}     !"android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile"
RewriteRule ^                       -                        [skip=3]
RewriteRule ^(index.html)?$         http://m.example.com     [L,R=301]
RewriteRule ^page-([123])/$         http://m.example.com/p$1 [L,R=301]
RewriteRule ^category/page-([45])/$ http://m.example.com/p$1 [L,R=301]
</IfModule>
# END mobile redirects

顺便说一句,从运行时的角度考虑这一点是一种误解。是的,每个正则表达式/规则将增加 10 秒的 μS,但在性能方面真正受到影响的是首先需要打开和读取 .htaccess 文件,any .htaccess 文件。做这种事情是为了清晰和易于维护。只要你不因为“太聪明”而自取其辱,规则的行数越少,隐藏错误的机会就越少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2020-05-07
    • 2011-11-05
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多