.htaccess文件用于多个控制空间和通配符子域

时间:2014-03-07 17:15:51

标签: .htaccess mod-rewrite redirect wildcard

我似乎无法理解配置基于子域发送到不同控制页面的.htaccess文件,然后将通配符用于用户子域。

我真正需要的是:

  1. 如果是domain.com,请重定向到www.domain.com/index.php
  2. 如果是www.domain.com,请重写为www.domain.com/index.php
  3. 如果是img.domain.com,请重写为www.domain.com/img/
  4. 如果是api.domain.com,请重写为www.domain.com/api/index.php
  5. 如果是admin.domain.com,请重写为www.domain.com/admin/index.php

  6. 如果(其他任何内容).domain.com,请重写为www.domain.com/users/index.php - 同时将子域的值作为变量发送。

  7. 我见过的所有教程都将所有请求发送到单个页面然后被路由,我希望htaccess文件事先做一些工作。

1 个答案:

答案 0 :(得分:0)

如果您的子域未指向同一个documentroot的主域(您必须启用 mod_proxy

RewriteEngine on

# 1. www-rule: domain.com to www.domain.com
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# 2. skip www.domain.com
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule . - [L]

# 3/4/5. manage img, api and admin subdomains
RewriteCond %{HTTP_HOST} ^(img|api|admin)\. [NC]
RewriteRule ^(.*)$ http://www.domain.com/%1/$1 [P]

# 6. manage users
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$
RewriteRule ^(.*)$ http://www.domain.com/users/index.php?user=%1 [P]


如果你的子域指向同一个documentroot的主域(这里不需要mod_proxy)

RewriteEngine on

# 1. www-rule: domain.com to www.domain.com
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# 2. skip www.domain.com
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule . - [L]

# 3/4/5. manage img, api and admin subdomains
RewriteCond %{HTTP_HOST} ^(img|api|admin)\. [NC]
RewriteRule ^(.*)$ /%1/$1 [L]

# 6. manage users
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$
RewriteRule ^(.*)$ /users/index.php?user=%1 [L]

编辑:

RewriteEngine on

# 1. www-rule: redirect domain.com to www.domain.com
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# 2. www.domain.com rewritten to index.php
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule . /index.php [L]

# 3. img.domain.com rewritten to img folder
RewriteCond %{HTTP_HOST} ^img\. [NC]
RewriteRule ^(.*)$ /img/$1 [L]

# 4/5. api or admin subdomains rewritten to /api/index.php or /admin/index.php
RewriteCond %{HTTP_HOST} ^(api|admin)\. [NC]
RewriteRule . /%1/index.php [L]

# 6. manage users
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$
RewriteRule . /users/index.php?user=%1 [L]