Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 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 Reply

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...