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

为君一笑 提交于 2019-11-30 10:23:08
meberhard

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

This can be achieved in .htaccess without mod_proxy provided your server is configured to allow wildcard subdomains. (I achieved that in JustHost by creating a subomain manually named *). Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Chetabahana

I named the subdirectories under $_SERVER['DOCUMENT_ROOT'] match with my subdomains like so:

/
 var/
     www/
         html/
              .htaccess
              subdomain1.domain.com/
              subdomain2.domain.com/
              subdomain3.domain.com/

Where /var/www/html stand as 'DOCUMENT_ROOT'. Then put following code in the .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/%{HTTP_HOST}/
RewriteRule (.*) /%{HTTP_HOST}/$1 [L]

It works as redirect wildcard subdomains to subdirectories, without changing URL in address bar.

Beside of vhost, you may also put the subdirectories outside root and access it using alias as described here. Then put the same .htaccess code in that location.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!