2016-06-21 65 views
0

我有這樣的Apache重寫規則:追加查詢字符串中使用htaccess的URL重寫不工作

RewriteCond %{QUERY_STRING} !lang 
RewriteCond %{HTTP_HOST} ^(jp|en|kr|cn)\.example\.com 
RewriteRule ^(.*)$ http://%1.example.com/$1&lang=%1 [L, QSA] 

RewriteCond %{HTTP_HOST} ^(jp|en|kr|cn)\.example\.com 
RewriteRule ^(.*)$ http://%1.example.com/$1?lang=%1 [L, QSA] 

我的預期是什麼

  1. http://en.example.comhttp://en.example.com?lang=en
  2. http://en.example.com/list.phphttp://en.example.com/list.php?lang=en
  3. http://en.example.com/product.php?id=1http://en.example.com/product.php?id=1&lang=en

(1)和(2)是好的,但我得到了(3)是

http://en.mobile-wifi_rental.local/product.php&lang=en?id=1

回答

1

你只需要一個規則,對於這一點,那就是:

RewriteEngine on 
RewriteBase/

RewriteCond %{QUERY_STRING} !lang 
RewriteCond %{HTTP_HOST} ^(jp|en|kr|cn)\.example\.com$ 
RewriteRule ^(.*)$ http://%1.example.com/$1?lang=%1 [L,QSA] 

與你的第一個規則的問題是對的查詢字符串使用&代替?

它的一個通用版本是:

RewriteCond %{QUERY_STRING} !lang 
RewriteCond %{HTTP_HOST} ^([a-z]{2})\.[^\.]+\.[^\.]+$ 
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1?lang=%1 [L,QSA] 
+0

在我情況下,它不需要是通用的。我可以使用確切的國家代碼('jp | en | kr | cn')和域名('example.com')。 – Sithu

+0

它在http://htaccess.mwl.be/嘗試了您的通用規則。 'http://en.example.com/product.php?id = 1'不添加'id = 1'。結果是'http://en.example.com/product.php?lang = en'。我想要的是像'http://en.example.com/product.php?id = 1&lang = en' – Sithu

+0

是的,我只需要一條規則,它可以在真實的現場服務器上運行,在線測試器http:// htaccess.mwl.be/不僅僅按預期工作。 – Sithu

1

我改變了你的規則,%{QUERY_STRING}手動添加:

RewriteCond %{QUERY_STRING} !lang 
RewriteCond %{HTTP_HOST} ^(jp|en|kr|cn)\.example\.com 
RewriteRule ^$ http://%1.example.com/?lang=%1 [L,QSA] 

#Rule for empty query string 
RewriteCond %{QUERY_STRING} ^$ 
RewriteCond %{HTTP_HOST} ^(jp|en|kr|cn)\.example\.com 
RewriteRule ^(.*) http://%1.example.com/$1?lang=%1 [L] 

RewriteCond %{QUERY_STRING} !lang 
RewriteCond %{HTTP_HOST} ^(jp|en|kr|cn)\.example\.com 
RewriteRule ^(.*) http://%1.example.com/$1?%{QUERY_STRING}&lang=%1 [L] 

測試了字符串:http://en.example.com/product.php?id=1,其結果是http://en.example.com/product.php?id=1&lang=en

+0

它幾乎可以工作。我在http:// en.example.com/product.php上http://htaccess.mwl.be/上試了一下。輸出結果是'http://en.example.com/product.php?&lang = en',帶有額外的'&' – Sithu

+0

因爲它需要額外的規則來檢查query_string是否爲空。 –

+0

@Sithu我添加了一個額外的規則來驗證查詢字符串是否爲空。經測試! –