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
450 views
in Technique[技术] by (71.8m points)

.htaccess - htaccess subdomain

Howto make this with htacess:

subdomain.domain.com -> domain.com/subdomain (no redirect on client side)
domain.com/subdomain -> subdomain.domain.com (redirect)

I make firs redirect:

RewriteRule ^subdomain/ - [L]
RewriteCond %{HTTP_HOST} ^subdomain.domain.com [NC]
RewriteRule (.*) subdomain/$1 [L]

How is it inserted in the form htacess:

AddDefaultCharset utf-8
DirectoryIndex index.php index.html index.htm
Options All -Indexes
ErrorDocument 404 /404.html
ErrorDocument 403 /404.html
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
RewriteCond %{REQUEST_URI} !.(png|jpg|jpeg|gif)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$  index.php/$1 [QSA]
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is a wildcard based solution, so it sould work for any number of subdomains.

This will redirect domain.com/foo/bar to foo.domain.com/bar:

RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ([^/]+)(/.*|$) $1.domain.com/$2 [R=302]

This will handle (internal rewrite) the virtual hosts:

RewriteCond %{HTTP_HOST} ^(.*).domain.com$ [NC]
RewriteRule (.*) %1/$1 [L]

You might consider using 301 (permanent redirect) instead of the 302.

I strongly suggest you have a VirtualHost for your main site domain.com or www.domain.com and a separate one for handling the virtual subdomains.

For only a certain subdomain:

RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule (subdomain)(/.*|$) $1.domain.com/$2 [R=302,L]

RewriteCond %{HTTP_HOST} ^(subdomain).domain.com$ [NC]
RewriteRule (.*) %1/$1 [L]

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

...