Search code examples
phpapache.htaccessubuntusubdomain

Dynamic subdomain pages with .htaccess or PHP


I have my directory like this:

  • /index.php (website main page)
  • /sites
    • site1
    • site2
    • site3

  1. when I go to site1.example.com, i want it to show example.com/sites/site1/index.php

  2. when I go to site1.example.com/page1, i want it to show the file example.com/sites/site1/page1.php

how can i do that? thanks!


Solution

  • I assume all your subdomains point to the same place as the main domain, so subdomain.example.com and example.com point to the same place.

    Try something like the following in the .htaccess file in the root of the main site:

    RewriteEngine On
    
    # Exclude requests for the www subdomain
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteRule ^ - [L]
    
    # Requests for the site root
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
    RewriteRule ^$ sites/%1/index.php [L]
    
    # Requests that are "assumed" to be .php files
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
    RewriteRule ^([^.]*)$ sites/%1/$1.php [L]
    
    # All other requests
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
    RewriteRule !^sites/ sites/%1%{REQUEST_URI} [L]
    

    This assumes that a valid URL-path does not contain a dot.

    %1 is a backreference to the captured group in the CondPattern (ie. the subdomain) and $1 is a backreference to the captured group in the RewriteRule pattern.

    However, how do you want to handle non-PHP files and other static resources?


    Also, how can I do a 404 page?

    You can define a custom error document. For example:

    ErrorDocument 404 /errors/404.php
    

    However, you'll need to make an exception at the top of your .htaccess file to prevent this from being rewritten by the directives that follow. For example:

    RewriteRule ^errors/ - [L]