获取url参数/ URL重写

时间:2014-07-16 06:49:16

标签: apache .htaccess url-rewriting

我想使用URL重写来拥有“虚拟”子域。我已经创建了通配符DNS条目。

我希望将子域名添加为GET参数。

示例:

http://mysubdomain.domain.com/index.php

会打电话:

http://www.domain.com/index.php?subdomain=mysubdomain

http://mysubdomain.domain.com/page.php?parameter1=parameter

会打电话:

http://www.domain.com/page.php?parameter1=parameter&subdomain=mysubdomain

这是我的.htaccess文件:

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]

RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+).domain.com$ [NC]
RewriteRule ^$ /index.php?subdomain=%2 [L]

RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+).domain.com$ [NC]
RewriteRule ^([A-Za-z0-9_.]+)$ /$1 [L]

它有效,但我无法获得子域值,当调用其他页面而不是index.php时,如果我调用http://subdomain.domain.com/page.php我松散了子域参数,我试过:

RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+).domain.com$ [NC]
RewriteRule ^([A-Za-z0-9_.]+)$ /$1&subdomain=%2 [L]

但我得到了内部错误。

1 个答案:

答案 0 :(得分:0)

这是规则:

RewriteRule ^$ /index.php?subdomain=%2 [L]

需要QSA标志:

RewriteRule ^$ /index.php?subdomain=%2 [L,QSA]

和这条规则:

RewriteRule ^([A-Za-z0-9_.]+)$ /$1 [L]

需要QSA标志和正确的反向引用:

RewriteRule ^([A-Za-z0-9_.]+)$ /$1?subdomain=%2 [L,QSA]