Search code examples
php.htaccesshostname

Catching the domain name with .htaccess


I'm quite new in using .htaccess and modrewrite.

I have a multitenant website in php and every tenant can save a domain name he bought in the app database after pointing it to my server ip.

Now I'm trying to write a rewrite Rule via .htaccess so that when the user types his domain in the addressbar (e.g. www.example.com) the .htaccess parses the hostname and passes it as a parameter to an index page, so that every request done to www.example.com becomes something like that: /index.php?domain=www.example.com .

And even www.example.com/user to become /index.php?domain=www.example.com&url=user

How can I do it with .htaccess?

Thank you for your help !


Solution

  • You may use this rule in your site root .htaccess:

    RewriteEngine On
    
    RewriteCond %{QUERY_STRING} !domain= [NC]
    RewriteRule ^(?:index\.php)?$ index.php?domain=%{HTTP_HOST} [L,QSA,NC]
    
    RewriteCond %{QUERY_STRING} !domain= [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php?domain=%{HTTP_HOST}&url=%{REQUEST_URI} [L,QSA]