views:

36

answers:

1

I need to redirect web requests of the form /{language}-{country}/{file} to:

  1. /{language}-{country}/{file} if it exists, otherwise
  2. /{language}/{file} if it exists, otherwise
  3. /en-US/{file}

The existing .htaccess fulfils requirements 1 and 3. What changes do I need to fulfil requirement 2?

.htaccess:

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

Update:

My new .htaccess meets the functional requirement but seems over-complicated. How can I simplify it?

# 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  A: 

Try this:

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]

But this rule does only work is used in the .htaccess file in the document root.

Gumbo
What do $1 and $3 contain in line 3?
Anthony Faull
@Anthony Faull: They contain the match of the first/third group of the pattern of `RewriteRule`. `$n` does always refer to the matches of the corresponding `RewriteRule`.
Gumbo
Your suggestion may work. But first I need to understand some of the details. What is the first line for? What's the difference between $1 and %1? Can you point me to some good documentation on mod_rewrite?
Anthony Faull
@Anthony Faull: The first line is just to get the value of `$0` into `%0` so that I can use it in the substitution part of `RewriteRule`. `$1` references the match of the first group in the corresponding `RewriteRule` while `%1` references the match of the first group of the last successful `RewriteCond` match. So `$n` refers to `RewriteRule` and `%n` to the last successful `RewriteCond`.
Gumbo
@gumbo Thanks for your explanation. That helped a great deal.
Anthony Faull