質問

I can't seem to get my head around configuring an .htaccess file that sends to different control pages based on the subdomain, then uses wildcards for user subdomains.

What I need is essentially this:

  1. If domain.com, redirect to www.domain.com/index.php
  2. If www.domain.com, rewrite to www.domain.com/index.php
  3. If img.domain.com, rewrite to www.domain.com/img/
  4. If api.domain.com, rewrite to www.domain.com/api/index.php
  5. If admin.domain.com, rewrite to www.domain.com/admin/index.php

  6. If (anything else).domain.com, rewrite to www.domain.com/users/index.php - also sending the value of the subdomain as a variable.

All of the tutorials I've seen send all requests to a single page which is then routed, I would like the htaccess file to do some of the work beforehand.

役に立ちましたか?

解決

If your subdomains are not pointing to same documentroot's main domain (you will have to enable 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]


If your subdomains are pointing to same documentroot's main domain (mod_proxy is not needed here)

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]

EDIT:

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]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top