2016-06-21 29 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我添加了一个额外的规则来验证查询字符串是否为空。经测试! –

相关问题