RewriteCond检查父目录上是否存在文件

时间:2013-06-08 15:01:43

标签: php apache .htaccess parent

如果请求的文件或目录不存在,我正在尝试将所有请求重定向到脚本,但我需要改进此.htaccess以检查父文件夹中是否存在该文件。
我目前有:

RewriteEngine on

# check if requested file or directory exists
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# map requests to contentpage.php and appends it as a query string
RewriteRule ^(.*)/(.*)$ contentpage.php?url=$2&lang=$1

现在,此.htaccess成功重定向了 en / products.php - >如果 products.php 在子目录/ en /上不存在,则 contentpage.php?url = products.php& lang = zh_CN (实际上目录/ en /实际上并不存在,所以当我在父目录中有一个文件 products.php 时,RewriteCond无法过滤。)

我需要检查文件是否存在于我的文件所在的顶级目录中。它只需要重定向语言目录,比如/ en / es / de / pt .etc

任何人都知道如何解决这个问题?感谢

1 个答案:

答案 0 :(得分:1)

您可以将规则放在顶层目录中的htaccess文件中;这样,如果你有

 /parentdir
     /en
     /es 
     /de

即使您访问父路径或子路径:

  • /parentdir/products.php
  • /parentdir/en/products.php

评估/parentdir/.htaccess规则
所以你可以使用这样的规则集:

# check if requested file does not exists in the child dir
# check if requested file does not exists in the child dir
# if does not exists... check if it also does not exists in the parent dir
RewriteCond /parentdir/$1/$2 !-f
RewriteCond /parentdir/$2 !-f
RewriteRule ^/parentdir/(es|en|fr|de)/(.*)$ contentpage.php?url=$2&lang=$1

# check if requested file does not exists in the parent dir
RewriteCond /parentdir/$1 !-f
RewriteRule ^/parentdir/(.*)$ contentpage.php?url=$2&lang=$1