.htaccess for language detection, redirecting + clean urls

风格不统一 提交于 2019-12-13 06:23:37

问题


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]


来源:https://stackoverflow.com/questions/21453052/htaccess-for-language-detection-redirecting-clean-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!