大网数据广告活动
网站运营与故障问答

Use .htaccess to rewrite any subdomain to the corresponding subdir without revealing the subdir

· 52CE 我爱测

I have a little problem with my .htaccess . For example, if I go to test.example.com , it's in folder /sub/test . But it shows test.example.com/sub/test . How can I hide the path after .com ? Or is there any way to do it with Apa…

问题原文

原帖链接 · Oggy mot · CC BY-SA 3.0

I have a little problem with my .htaccess. For example, if I go to test.example.com, it's in folder /sub/test. But it shows test.example.com/sub/test. How can I hide the path after .com? Or is there any way to do it with Apache, like all folders in sub folder are subdomains?

I don't know how to do it.

I'm using this:

RewriteCond %{HTTP_HOST} ^((?!www\.).+?)\.example\.com$ [NC]
RewriteRule ^((?!sub/).*)$ /sub/%1/$1 [L]

EDIT: I want to make every created folder in sub folder as a subdomain automatically. Like user create folder and it's subdomain.

已采纳解答

原帖链接 · Patrick Mevzek · CC BY-SA 3.0

Remove your rules and just have something like:

<VirtualHost IP>
    ServerName test.example.com
    DocumentRoot /whatever/sub/test

(replace whatever by the correct path, and IP by the relevant IP/port based on how your virtualhosts are configured)

For dynamic virtual host have a look at module mod_vhost_alias http://httpd.apache.org/docs/2.4/mod/mod_vhost_alias.html), quoting from documentation:

For simple name-based virtual hosts you might use the 
following directives in your server configuration file:

UseCanonicalName    Off
VirtualDocumentRoot "/usr/local/apache/vhosts/%0"

A request for http://www.example.com/directory/file.html will be 
satisfied by the file
/usr/local/apache/vhosts/www.example.com/directory/file.html.

Otherwise, for your rewrite rules, it may work just by adding [P] as flag, but as a general rule I always recommend to find simpler ways to do things and use rewriting only if things can not be done otherwise (due to the complexity it adds).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2017-11-28)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。