.htaccess redirect to language subfolder

2019-05-19 14:48发布

问题:

What I have:

  • there are two languages installed: German and English
  • language-versions are managed with subfolders (www.domain.com/de/ and www.domain.com/en/)
  • machine: Typo3 4.5.4 / RealUrl installed
  • mod_rewrite is enabled an works

What I want to do:

  • redirect requests without language subfolder to the German version
  • e.g. domain.com/any/test/folder/ to domain.com/de/any/test/folder

What I tried:

RedirectMatch permanent ^/(?!(?:(?:de|en)/))(.*)$ /de/$1

Occuring problems:

  • all requests were directed to domain.com/de/index.php
  • it caused an error 310 (net::ERR_TOO_MANY_REDIRECTS)
  • maybe it fails with Typo3's htaccess entries?

my hole .htaccess-file:

# Enable URL rewriting
RewriteEngine On

# Change this path, if your TYPO3 installation is located in a subdirectory of the website root.
# RewriteBase /

# Rule for versioned static files, configured through:
# - $TYPO3_CONF_VARS['BE']['versionNumberInFilename']
# - $TYPO3_CONF_VARS['FE']['versionNumberInFilename']
# IMPORTANT: This rule has to be the very first RewriteCond in order to work!
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ $1.$3 [L]

# Stop rewrite processing, if we are in the typo3/ directory.
RewriteRule ^(typo3/|t3lib/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L]

# Redirect http://example.com/typo3 to http://example.com/typo3/index_re.php and stop the rewrite processing.
RewriteRule ^typo3$ typo3/index_re.php [L]

#301 redirection for language mode
RedirectMatch permanent ^/(?!(?:(?:de|en)/))(.*)$ /de/$1

# If the file/symlink/directory does not exist => Redirect to index.php.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

# Main URL rewriting.
RewriteRule .* index.php [L]

So, what can I do?

回答1:

What about this:

RewriteRule ^/?(?!de/|en/)(.*) /de/$1 [L,R=301]


回答2:

Why don't you use something more simple, like this:

# if user didn't specify a valid language subfolder
RewriteCond %{REQUEST_URI} !^/(en|de)/
# redirect user to default language subfolder
RewriteRule ^(.*)$ /de/$1 [L,R=301]


回答3:

You actually don't need to use htacces as you can configure this behaviour in your realUrl configuration. Just define this part in your config array:

    'preVars' => array(
      array(
        'GETvar' => 'L',
        'valueMap' => array(
            'de' => '0',
            'en' => '1',
            'fr' => '2',
            ),
        'valueDefault' => 'de',
        ),
),

This will give you a redirect to ../de/...