2014-02-23 97 views
2

我知道以前也有类似的问题,但我发现的解决方案似乎都没有解决。我是mod_rewrite的专家,如果我错过了一些明显的东西,我很抱歉。正确地将一个子域名重定向到子目录

我试图无形地将子域重定向到子目录中的index.php文件;此文件将子域的值作为查询字符串的一部分,该字段工作正常。

我遇到的问题是,现在一切该子目录被重定向到index.php文件,我不希望发生的事情。

这是我迄今:

RewriteEngine On 
RewriteBase/

# User dashboards 
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com [NC] 
RewriteRule ^.*$ app/index.php?user=%1 [L,NC,QSA] 

我正在寻找的是一个情况http://subdomain.example.com/会导致/app/index.php?user=subdomain,但http://subdomain.example.com/assets/stylesheet.css会去/app/assets/stylesheet.css

在此先感谢!

回答

0

如果我深知你的榜样,你可以这样做:

  1. 重定向的example.com www.example.com,以避免“空”子域

  2. 内部重写每根子域(除了WWW),以/app/index.php?user=subdomain

  3. 内部改写其他的东西与 “应用” 前缀


将由该代码

RewriteEngine on 

# redirects example.com to www.example.com to avoid having "empty" subdomain 
RewriteCond %{HTTP_HOST} ^example.com$ 
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] 

# internally rewrites every root subdomains (except www) to /app/index.php?user=subdomain 
RewriteCond %{HTTP_HOST} !^www\. [NC] 
RewriteCond %{HTTP_HOST} ^([^.]+)\. [NC] 
RewriteRule ^/?$ /app/index.php?user=%1 [L,NC,QSA] 

# internally rewrites other things with "app" prefix 
RewriteCond %{THE_REQUEST} !app/ 
RewriteRule ^/?(.+)$ /app/$1 [L,NC,QSA] 

编辑表示:当你问下面的评论,在这里是如何也管理www子域

RewriteEngine on 

# redirects example.com to www.example.com to avoid having "empty" subdomain 
RewriteCond %{HTTP_HOST} ^example.com$ 
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] 

# internally redirects www subdomain root to /site/index.php 
RewriteCond %{HTTP_HOST} ^www\. [NC] 
RewriteRule ^/?$ /site/index.php [L] 

# internally rewrites every other root subdomains to /app/index.php?user=subdomain 
RewriteCond %{HTTP_HOST} ^([^.]+)\. [NC] 
RewriteRule ^/?$ /app/index.php?user=%1 [L,NC,QSA] 

# internally rewrites other things with "app" prefix 
RewriteCond %{THE_REQUEST} !app/ 
RewriteRule ^/?(.+)$ /app/$1 [L,NC,QSA] 
+0

这解决了我的问题! 是否可以指定www。子域名到不同的目录呢? – querkmachine

+0

是的。 www子域的规则是什么? –

+0

它可以(类似地不可见)重定向到'/ site'之类的东西吗? – querkmachine

0

让我们添加第二个规则,以资产重定向到应用程序/资产:

RewriteCond %{HTTP_HOST} ^(.*)\.example\.com [NC] 
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|gif)$ [NC] 
RewriteRule ^.*$ app/index.php?user=%1 [L,QSA] 
RewriteRule ^assets/(.*)$ app/assets/$1 [L,QSA] 

,或者直接从应用程序加载所有的CSS/JS /图片:

RewriteCond %{HTTP_HOST} ^(.*)\.example\.com [NC] 
RewriteRule ^.*\.(css|js|png|jpg|gif)$ app/$0 [NC, QSA] 
RewriteRule ^.*$ app/index.php?user=%1 [L,QSA] 

编辑:对不起,我的天堂之前没有测试过,所以有工作示例:

RewriteRule ^assets/(.*)$ app/assets/$1 [L,QSA] 
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com [NC] 
RewriteRule !^app/assets/ app/index.php?user=%1 [L,QSA] 
+0

对不起,第一个例子似乎不已经改变了什么,第二个是给我一个500内部服务器错误消息。 – querkmachine

+0

对不起,我添加了新的可行示例 –

相关问题