如果文件存在,则重写URL

时间:2010-06-10 07:48:37

标签: .htaccess mod-rewrite

我需要将/{language}-{country}/{file}格式的网络请求重定向到:

  1. /{language}-{country}/{file}如果存在,否则
  2. /{language}/{file}如果存在,否则
  3. /en-US/{file}
  4. 现有.htaccess符合要求1和3.我需要做哪些更改才能满足要求2?

    .htaccess

    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond $0 !i18n/en-US [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(i18n)/([^/]+)/(.*)$ $1/en-US/$3 [NC,L]
    

    更新

    我的新.htaccess符合功能要求,但似乎过于复杂。我该如何简化它?

    # If not exists {language}-{country}, try {language}
    RewriteCond $0 i18n
    RewriteCond $0 !en-us
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond $0 ^(.*)(i18n)/(\w+)(-\w+)*/(.*)$
    RewriteCond E:/webserver/app/$2/$3/$5 -f
    RewriteRule ^(.*)(i18n)/(\w+)(-\w+)*/(.*)$ /app/$2/$3/$5 [L]
    
    # If not exists {language}-{country} or {language}, try /en-us/
    RewriteCond $0 i18n
    RewriteCond $0 !en-us
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond $0 ^(.*)(i18n)/(\w+)(-\w+)*/(.*)$
    RewriteCond E:/webserver/app/$2/$3/$5 !-f
    RewriteCond E:/webserver/app/$2/en-us/$5 -f
    RewriteRule ^(.*)(i18n)/(\w+)(-\w+)*/(.*)$ /app/$2/en-us/$5 [L]
    

1 个答案:

答案 0 :(得分:2)

试试这个:

RewriteCond $0 .+
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond i18n/$1/$3 .+
RewriteCond %{DOCUMENT_ROOT}/%0 -f [OR]
RewriteCond i18n/en-US/$3 .+
RewriteRule ^i18n/([a-zA-Z]{2})-([a-zA-Z]{2})/(.*) %0 [L]

但是这条规则只能用于文档根目录中的.htaccess文件。