Apache Rewrite: How to write a rule based on domain name (instead of HTTP_HOST)

apache-2.2mod-rewrite

I have written a RewriteRule which works on the basis of HTTP_HOST (www.domainname.com), but I want it to work on the basis of the domain name part only (domainname.com).

To clarify further

The folder structure is /var/www/domainName.com.

When I write this rule in apache conf file

RewriteRule ^/js/(.*) /%{HTTP_HOST}/js/$1 [L]

and access the site using www.mydomain.com — it tries to find the folder /var/www/www.domainName.com, which does not exist.

So, I need to convert the above-mentioned rule to remove the "www" from the HTTP_HOST.

Best Answer

I would suggest that you redirect requests rather than make the same site available in two places. Either create a new VirtualHost to redirect traffic:

<VirtualHost *:80>
    ServerName www.domainName.com
    Redirect / http://domainName.com/
</VirtualHost>

Or add a set of rules above your others that will detect the presence of the www. prefix and redirect the user:

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule /(.*) http://%1/$1 [R,L]

If you really want your site on both domain names without any redirection, you can use a RewriteCond to pull out just the domain name, and it will be available to the RewriteRule as %1.

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*) [NC]
RewriteRule ^/js/(.*) /%1/js/$1 [L]
Related Topic