Search code examples
.htaccessmod-rewriteapache2document-root

Abstraction of Apache VirtualHost URL's


So I have a couple of mod_rewrite rules to make URL's prettier.

By this I mean I wish to change a url that is entered as such:

http://test.domain.com/cheese/wine/

to a background association towards the test.php as such:

http://test.domain.com/test.php?client=test&page=cheese/wine

PS: The client variable above is actually the [test].domain.com.

According to the rewrite log all the RewriteRule's seem to work fine but all I get is a 400 error.


vHost file:

<VirtualHost *:80>
  ServerName *.domain.com
  DocumentRoot /var/www/dir/

  ...

  RewriteEngine on

  # drop www. from subdomains
  RewriteCond %{HTTP_HOST} ^www\.(.*)\.domain.com$
  RewriteRule ^/?(.*)$ http://%1.domain.com/$1 [R=301]

  # rewrite x.domain.com/abc to abc?client=x
  RewriteCond %{HTTP_HOST} ^([^.]+)\.domain.com$
  RewriteRule ^/?(.*)$ $1?client=%1 [QSA]

  RewriteRule ^/?(.*)$ test.php?page=$1 [QSA,L]

  ...
</VirtualHost>

Does anyone have any ideas?


Edit: The request hostname (*.domain.com) needs to stay intact because (www.)domain.com is treated in a different manner.


Solution

  • Your code generates an infinite loop.

    <VirtualHost *:80>
      ServerName *.domain.com
      DocumentRoot /var/www/dir/
    
      ...
    
      RewriteEngine on
    
      # drop www. from subdomains
      # also drop www. from main domain
      RewriteCond %{HTTP_HOST} ^www\.(.*\.)?domain.com$
      RewriteRule ^/?(.*)$ http://%1domain.com/$1 [R=301]
    
      # rewrite x.domain.com/abc to abc?client=x
      RewriteCond %{REQUEST_URI} !^test\.php
      RewriteCond %{HTTP_HOST} ^([^.]+)\.domain.com$
      RewriteRule ^/?(.*)$ test.php?page=$1&client=%1 [QSA,L]
    
      ...
    </VirtualHost>
    

    I also modified the code so www.domain.com/ redirect to domain.com/