2012-07-23 124 views
1

我正在閱讀與此主題相關的所有問題,但找不到任何內容。htaccess +根據瀏覽器語言重定向用戶

首先,我有這樣的域名:www.example.com

我的目的是根據用戶對瀏覽器的語言來重定向:

例如:www.example.com => www.example .COM/ES www.example.com => www.example.com/en

我遵循這個規則,但這裏是不是源網址:

<IfModule mod_rewrite.c> 
RewriteEngine on 
RewriteCond %{HTTP:Accept-Language} ^es [NC] 
RewriteCond %{HTTP_REFERER} !^*\.domain\.com.ar/ [NC] 
RewriteRule ^$ http://www.example.com/es/[L,R] 
RewriteCond %{HTTP:Accept-Language} ^en [NC] 
RewriteCond %{HTTP_REFERER} !^*\.domain\.be/ [NC] 
RewriteRule ^$ http://www.example.com/en/[L,R] 
</IfModule> 
+0

什麼是不工作? – 2012-07-23 15:23:03

+0

在這段代碼中,哪裏設置了目標網站?我的意思是......如果用戶想要訪問此網站:www.example.com,我需要根據瀏覽器的語言將他重定向到www.example.com/es或www.example.com/en。 – m4g4bu 2012-07-23 19:53:49

回答

0

在這段代碼中,哪裏設置了目標網站?

這裏:

RewriteRule ^$ http://www.example.com/es/[L,R] 

這裏:

RewriteRule ^$ http://www.example.com/en/[L,R] 

不知道如果這是一個錯字或如果這是你在你的htaccess的文件,但是這將產生500內部服務器錯誤,因爲你給RewriteRule 4參數,當它只想要2或3.

另一個問題我與你的%{HTTP_REFERER}正則表達式。 Apache可能會在這裏嘔吐:^*\.domain\.com.ar/,你可能意思是:^[^/]*\.domain\.com.ar/什麼的。所以,你可能希望你的規則是這樣的:

<IfModule mod_rewrite.c> 
RewriteEngine on 
RewriteCond %{HTTP:Accept-Language} ^es [NC] 
RewriteCond %{HTTP_REFERER} !^[^/]*\.domain\.com.ar/ [NC] 
RewriteRule ^$ http://www.example.com/es/ [L,R] 
RewriteCond %{HTTP:Accept-Language} ^en [NC] 
RewriteCond %{HTTP_REFERER} !^[^/]*\.domain\.be/ [NC] 
RewriteRule ^$ http://www.example.com/en/ [L,R] 
</IfModule> 

當然,你會用正確的主機名來替換的domain.com.ardomain.bewww.example.com實例。

另請注意:Accept-Language標頭是一個複雜的限定符字符串。它不像enes那麼簡單。西班牙網頁瀏覽器可能包含enes,只是因爲它們都是支持的語言。根據這個頭文件確定一個確切的語言重定向到的地方並不在mod_rewrite和htaccess的範圍內。

+0

,但如果用戶在瀏覽器中輸入:www.example.com,我想將用戶重定向到:www.example.com/es或www.example.com/en。上面提供的代碼不起作用 – m4g4bu 2012-07-23 22:34:31

0

如果您要檢查域和瀏覽器的語言,這是你可以做什麼:

# Check domain (1), browser language (2) and redirect to subdirectory (3) 
RewriteCond %{HTTP_HOST} .*example.com [NC] 
RewriteCond %{HTTP:Accept-Language} ^en [NC] 
RewriteRule ^$ http://%{HTTP_HOST}/en/ [L,R=301] 

# ... copy block above for other languages ... 

# Fallback for any other language to spanish 
RewriteCond %{HTTP_HOST} .*example.com [NC] 
RewriteRule ^$ http://%{HTTP_HOST}/es/ [L,R=301] 
相關問題