Search code examples
.htaccessvariablesurl-rewriting

.htaccess rewrite a subdomain with a variable


Is this possible point a subdomain to specific variable?

http://whatever.example.com point to http://example.com/file.php?var=1

http://whatever1.example.com point to http://example.com/file.php?var=2

Tried the recommended answer below - the code work but no css style:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^(?:www\.)?whatever\.example\.com$
RewriteRule ^ /file.php?var=1 [L,QSA]

RewriteCond %{HTTP_HOST} ^(?:www\.)?whatever1\.example\.com$
RewriteRule ^ /file.php?var=2 [L,QSA]

or

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\.example\.com$

RewriteCond %{HTTP_HOST} ^(?:www\.)?([^.]+)\.example\.com$

RewriteRule ^ /file.php?var=%1 [L,QSA]

Got it working by adding <base href=""/>in header and making a folder called cssfolder for my css because root folder wasn't working. I dont know why?

<base href="../" /> "not working"

<base href="/" /> "not working"

<base href="./" /> "not working"

<base href="/cssfolder/" /> "this work"

Solution

  • Sure that is possible. But you need to tell a few things apart:

    The actual host name in the URL ("subdomain") is not part of the path a RewriteRules pattern is internally matched against. You need to use a RewriteCond to access that information:

    RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^(?:www\.)?whatever\.example\.com$
    RewriteRule ^ /file.php?var=1 [L,QSA]
    
    RewriteCond %{HTTP_HOST} ^(?:www\.)?whatever1\.example\.com$
    RewriteRule ^ /file.php?var=2 [L,QSA]
    

    A typical variant would be to hand over an actual name instead of a numeric value. Here the GET variable would become v=whatever or v=whatever1:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.com$
    RewriteCond %{HTTP_HOST} ^(?:www\.)?([^.]+)\.example\.com$
    RewriteRule ^ /file.php?var=%1 [L,QSA]
    

    This assumes that all hosts/subdomains are served from by same http server, of course, since it is an internal rewrite.

    In general I would recommend that you take a look at the documentation of the tools you want to use. That documentation is, as typical for OpenSource software, of excellent quality and comes with great examples: https://httpd.apache.org/docs/current/mod/mod_rewrite.html