Rewrite all virtual subdomains to same folder usin

2020-06-28 09:34发布

问题:

I have been searching the internet trying to find a solution to this problem but cannot find a definite solution.

I am trying to redirect rewrite

anything.domain.com/anypage.php?sub=anything&including=get_parameters

to

domain.com/users/anypage.php?sub=anything&including=get_parameters


I have found several pages with possible solutions but they all differ slightly to my needs, and editing them continually ends in failure.

Any help would be much appreciated. Thank you.

P.S Wildcard DNS are enabled and everything is set up correctly in apache.

Edit:

I ended up using the folowing, it seems to work pretty well. Thanks.

RewriteCond %{HTTP_HOST}
^(.*).domain.com RewriteCond
%{HTTP_HOST} !^www.domain.com [NC]
RewriteRule ^(.*)$
http://domain.com/users/$1?sub=%1 [P]

回答1:

Try this rule in your .htaccess file:

Options +FollowSymLinks
RewriteEngine on

# redirect for http
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC]
RewriteCond %{SERVER_PORT} =80
RewriteRule ^(.*)$ http://domain.com/users/$1?sub=%1 [R=301,QSA,L,NE]

# redirect for https
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC]
RewriteCond %{SERVER_PORT} =443
RewriteRule ^(.*)$ https://domain.com/users/$1?sub=%1 [R=301,QSA,L,NE]

R=301 will redirect with https status 301
L will make last rule
NE is for no escaping query string
QSA will append your existing query parameters

$1 is your REQUEST_URI