title: .htaccess redirect + rewrite: Prefix uri with language code while keeping initial uri
body: <p>I am trying to rewrite/redirect incoming requests so that they will always be prefixed by a language code but would like to keep the originally requested path:</p>
  
  <pre><code>example.org/de/     -&gt; rewrite to example.org?lang=de
  example.org         -&gt; redirect to example.org/de/ which will then be rewritten
                         to example.org?lang=de
  example.org/en/     -&gt; rewrite to example.org?lang=en
  example.org/foo/bar -&gt; redirect to example.org/de/foo/bar wich will 
                         then be rewritten to example.org/foo/bar?lang=de
  </code></pre>
  
  <p>These were my thoughts on this:</p>
  
  <pre><code>RewriteBase /
  
  # No 'lang' key in query string 
  RewriteCond %{QUERY_STRING} !lang=(en|de) 
  
  # AND request_uri does not start with 'en' or 'de'
  RewriteCond %{REQUEST_URI} !^(en|de) 
  
  # Redirect to lang prefixed uri while keeping the initial uri
  RewriteRule ^(.*)$ de/%{REQUEST_URI} [L,R=301,QSA]
  
  # Add language prefix as query parameter
  RewriteRule ^(en|de) ?lang=$1 [L,QSA]
  </code></pre>
  
  <p>Furthermore I would like to keep any query strings of the incoming request and append it to the redirected/rewritten uri.
  Actually my thoughts sound logic to me but I'm getting an endless redirect. I would be too happy if you could point me in the right direction since I'm lost since hours and hours</p>
  
  <p><strong>Update</strong></p>
  
  <p>Finally with the help of anubhava I could manage to solve this whole issue and would like to share the final solution</p>
  
  <pre><code># 1) Prefix ALL request uris with /&lt;lang&gt;/. Depending on the `Accept-Language` 
  #    header 'de' or the default 'en' is used as prefix.
  # 2) Rewrite real files by stripping off the /&lt;lang&gt;/ prefix but still add 
  #    the ?lang=&lt;lang&gt; query parameter
  # 3) Add a trailing slash and append ?lang=&lt;lang&gt; query parameter
  
  
  RewriteEngine On
  
  RewriteBase /
  
  # No 'lang' key in query string and 'de' as accepted language header.
  # Redirect to 'de' prefixed uri
  RewriteCond %{QUERY_STRING} !lang=(en|de) [NC]
  RewriteCond %{HTTP:Accept-Language} (de) [NC]
  RewriteRule !^(en|de)(/.*)?$ de%{REQUEST_URI} [L,NC,R]
  
  # Redirect anybody without 'de' as accepted language to the 'en' version
  RewriteCond %{QUERY_STRING} !lang=(en|de) [NC]
  RewriteRule !^(en|de)(/.*)?$ en%{REQUEST_URI} [L,NC,R]
  
  # Strip lang prefix in case this a real file
  RewriteCond %{REQUEST_URI} ^/(en|de)(/.*)$ [NC]
  RewriteCond %{DOCUMENT_ROOT}%2 -f 
  RewriteRule ^(en|de)(/.*)$ $2?lang=$1 [L,NC]
  
  # Add trailing slash to those request which make it till here
  RewriteRule ^(en|de)(/.*)?/?$ $2/?lang=$1 [L,NC,QSA]
  </code></pre>
  
  <p>Thanks a lot for your help!</p>