【问题标题】:RewriteRule only if directory or file does not exists仅当目录或文件不存在时才重写规则
【发布时间】:2012-07-23 17:24:11
【问题描述】:

我正在尝试使用 php 和 .htaccess 创建一个 url 处理程序,我的问题是我不知道如何仅在 url 中输入的文件\目录不存在时使用重写条件。

【问题讨论】:

  • 你有没有尝试搜索过?
  • 嗯,我确实搜索过。

标签: php .htaccess redirect


【解决方案1】:

它与 shell 脚本的 -d 和 -f 函数非常相似。

试试这样的:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule XXX

【讨论】:

  • 表示:如果请求的文件名 是一个存在的文件 AND 是一个存在的目录
【解决方案2】:

请查看此RewriteCond 资源。

RewriteCond %{REQUEST_FILENAME} !-f
//                                ^ this means file.
RewriteCond %{REQUEST_FILENAME} !-d
//                              ^ this means NOT, "d" means directory.
// Your rewrite rule here.

【讨论】:

  • 请注意,这仅适用于 <Directory> 块或 .htaccess 文件,不适用于 <VirtualHost> 或根配置上下文,其中 REQUEST_FILENAME 尚未完成完整路径 (因为不知道)。在这些上下文中,必须手动将部分路径添加到测试中,因为 REQUEST_FILENAME 将与 REQUEST_URI 相同。
【解决方案3】:

'-d' (is directory) 将 TestString 视为路径名并进行测试 是否存在,是否为目录。

'-f'(是常规文件)将 TestString 视为路径名并进行测试 是否存在,是否为普通文件。

以感叹号 ('!') 为前缀以否定它们的含义。

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

【讨论】:

    【解决方案4】:

    应该这样做(替换<filename>):

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    
    RewriteRule .* <filename> [L]
    

    如果文件、目录或链接不存在,它会进行重定向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2015-09-09
      相关资源
      最近更新 更多