【问题标题】:Check REQUEST_URI with mod_rewrite使用 mod_rewrite 检查 REQUEST_URI
【发布时间】:2013-08-17 02:47:40
【问题描述】:

我尝试使用 mod_rewrite 来限制 REQUEST_URI 的长度,但我现在遇到了一些问题。 代码:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^(/[a-zA-Z0-9]{6}/?$)
RewriteRule ^ index.php [L]

它工作正常,所有 REQUEST_URI == lentgh(6) 都指向 index.php,但我需要所有不匹配的 REQUEST_URI 被禁止或重定向到 error.html,例如。

提前致谢。 我正在使用 Apache > 2.4.4

UPD 我的意思是这样的例子: If REQUEST_URI == len(6) 指向 index.php If REQUEST_URI != len(6) 重定向到另一个资源

【问题讨论】:

  • 我不太确定你在问什么。 What is the XY problem?。你这样做的实际目标是什么?你想让它也匹配文件吗?还是所有不存在的文件?
  • 我问是因为不知道如何拆分逻辑。如果匹配的 URI 指向 index.php,如果 不匹配 指向另一个资源(例如)
  • “但我需要所有不匹配的 REQUEST_URI 的禁止或重定向到 error.html”没有意义。你能举一些重定向的例子,以及你的目录结构吗?
  • 为什么“没有意义”?
  • 好的。我展示了简单的 ex:If REQUEST_URI == len(6) 指向 index.php If REQUEST_URI != len(6) 指向 google.com

标签: apache .htaccess mod-rewrite apache2


【解决方案1】:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/([a-zA-Z0-9]{6})$
RewriteRule .* index.php [L]

RewriteCond  %{REQUEST_URI}  !^/index.php
RewriteRule .*  404.php

【讨论】:

    【解决方案2】:

    一种方法是创建另一个使用否定前瞻的规则。

    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^(?!/[a-zA-Z0-9]{6}/?$)
    RewriteRule ^ http://google.com [L,R=301]
    
    RewriteCond %{REQUEST_URI} ^(/[a-zA-Z0-9]{6}/?$)
    RewriteRule ^ index.php [L]
    

    【讨论】:

    • 我不知道为什么,但第一个正则表达式对我不起作用。如果我先删除 ? ^(!/[a-zA-Z0-9]{6}/?$) 然后工作正常。
    • 老实说,如果@undone 的答案对您有用,请使用它。它比我的要好,而且性能会更好。
    • 是的,我同意你的看法。
    【解决方案3】:

    我针对我的情况提出了一个更优雅(并且可能更快)的解决方案。

    RewriteEngine On
    
    RewriteCond %{REQUEST_URI} [^/.]{7}
    RewriteRule ^ - [F]
    
    RewriteRule .* index.php [L]
    

    如果 REQUEST_URI 不是从 /index.php 开始或从根 '/' 开始并且长度 > 6 - 禁止,否则指向 index.php

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2011-09-29
      • 2015-04-28
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多