正确地将子域正确地重定向到子目录

时间:2014-02-23 12:18:44

标签: apache .htaccess mod-rewrite

我之前已经知道类似的事情,但我找到的解决方案似乎都没有解决。到目前为止,就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

提前致谢!

2 个答案:

答案 0 :(得分:0)

添加第二条规则,将资产重定向到app / assets:

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]

或直接从app加载所有css / js / images:

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]

答案 1 :(得分:0)

如果我理解你的榜样,你可以这样做:

  1. 将example.com重定向到www.example.com以避免出现“空”子域

  2. 在内部将每个根子域(www除外)重写为/app/index.php?user=subdomain

  3. 使用“app”前缀

  4. 在内部重写其他内容

    由此代码代表

    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]
    
相关问题