.htaccess for language detection, redirecting + cl

2019-09-05 17:54发布

问题:

I'm not very familiar with .htaccess, but i managed to put the following file together. Sadly it's not working..

What it had to do: - Detect if a user is french = redirect to example.com/fr - Detect if user is any other language = redirect to example.com/nl - Show all urls without .html and .php

This is the code i have for the language detection, but it loops..

    RewriteEngine on
    RewriteCond %{HTTP:Accept-Language} (fr) [NC]
    RewriteRule .* http://www.example.com/fr [R,L]
    RewriteRule .* http://www.example.com/nl [R,L]

And this is the code i have for the clean urls, but it's only for .html, and i need both for .html and .php

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.+)$ $1.html [L,QSA]

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
    RewriteRule ^(.*)\.html$ /$1 [R=301,L]

So how do i get both of these working, and put together in the same file? Greets.

回答1:

You need to check that you're not already in the /fr/ or /nl/ directories:

RewriteEngine on
RewriteCond %{HTTP:Accept-Language} (fr) [NC]
RewriteRule ^(?!fr/)(.*)$ http://www.example.com/fr/$1 [R,L]
RewriteRule ^(?!nl/)(.*)$ http://www.example.com/nl/$1 [R,L]

Then you simply need to duplicate your rules for both html and php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.(php|html)($|\?|\ )
RewriteRule ^(.*)\.(php|html)$ /$1 [R=301,L]