Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

apache - Redirect wildcard subdomains to subdirectory, without changing URL in address bar

I've read a lot of questions and answers about this on here but none that seem to solve my specific problem.

I want to redirect any subdomain to the subdirectory to match.

So: x.domain.com would go to domain.com/x, and y.domain.com would go to domain.com/y - But I want to do this without the URL in the address bar changing.

Here's what I have so far:

    Options +FollowSymLinks 

    RewriteEngine on

    RewriteBase /

    RewriteCond %{HTTP_HOST} !^(www). [NC]

    RewriteCond %{HTTP_HOST} ^(.*).domain.com [NC]

    RewriteRule ^ /%1 [P,L]

But this takes me to a website redirect loop, with an incorrect address in the URL bar where the subdomain still exists.

For example, x.domain.com takes me to x.domain.com/x and I get a redirect loop error.

I'd be grateful if anyone can point me in the right direction! Nothing I change seems to work...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, make sure that the vhost in the apache configuration is properly configured and all subdomains of domain.com are in the same host configuration (wildcard):

<VirtualHost *:80>
ServerName domain.com
ServerAlias *.domain.com
...

You can get the redirect working with the following htaccess configuration:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*).domain.com
RewriteRule ^(.*)$ http://domain.com/%1/$1 [L,NC,QSA]

Now, if you open asd.domain.com it should redirect you to domain.com/asd. You will still have the problem, that the redirect is visible in the URL address bar. In order to prevent this, enable mod_proxy (and load the submodules) on your server and exchange the "L" flag with the "P" flag:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*).domain.com
RewriteRule ^(.*)$ http://domain.com/%1/$1 [P,NC,QSA]

If this doesn't work, viewing the vhost configuration and the content of error.log on subdomain calling will be helpful!

References:
.htaccess rewrite subdomain to directory
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html
http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_p


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...