使用htaccess URL重写不起作用附加查询字符串

时间:2016-06-21 10:34:44

标签: apache .htaccess mod-rewrite

我有这个Apache Rewrite规则:

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
  4. (1)和(2)很好,但我得到的(3)是

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

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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

相关问题