I have hundreds of domains so I needed an htaccess that would force www without knowing the exact domain name.

I got it to work, but then it started forcing www in front of ALL my subdomain URLs too, not just domain.com (ex: ). So I need something that will force www only if the user inputs domain.com.

I tried tweaking my original code and it's not working. Any suggestions?

RewriteCond %{HTTP_HOST} ^%{HTTP_HOST}$ [NC]
RewriteRule ^(.*)$ [R=301,L]

Dani AI

Generated

— the problem is that a rule which says “if the host doesn’t start with www. then add it” will also match sub.domain.com. The trick is to only redirect hosts that look like a bare domain + TLD (for example domain.com) and ignore anything that already contains an extra label to the left.

Try a focused mod_rewrite snippet that captures only two-part hosts and prepends www. to that capture:

RewriteEngine On

# only when host doesn't already start with www
RewriteCond %{HTTP_HOST} !^www\. [NC]
# match exactly two labels (domain + tld) and capture them as %1
RewriteCond %{HTTP_HOST} ^([^.]+\.[^.]+)$
# redirect to www.<captured-host> keeping path and query
RewriteRule ^ http://www.%1%{REQUEST_URI} [R=301,L]

Notes and troubleshooting:

  • This handles typical names like domain.com and domain.net and will not touch sub.domain.com. It will not correctly detect multi-part public suffixes (for example domain.co.uk) — if you need those you must explicitly add those suffix patterns to the second condition or maintain a small list of exceptions.
  • Use R=302 while testing so browsers don’t cache a 301. Test with curl -I to inspect the Location header and confirm there are no loops.
  • If you can get your host to add a ServerAlias or set redirects at the vhost level (as suggested), that’s cleaner; on shared hosting you may have to stick with the .htaccess approach shown here.
  • Put the rules near the top of the .htaccess, ensure mod_rewrite is enabled, and watch for port numbers in HTTP_HOST (rare on standard ports).

Recommended Answers

All 3 Replies

I am just curious why you don't simply use a ServerAlias entry in the hpptd.conf file like most sites:

<VirtualHost *:80>
        ServerAdmin webmaster@txlinux.com
        DocumentRoot /var/www/html/txlinux.com
        ServerName txlinux.com
        ServerAlias www.txlinux.com
        ErrorLog logs/txlinux.com-error_log
        CustomLog logs/txlinux.com-access_log common
</VirtualHost>

shared hosting account - no access

Then you are going to have to request the addition of the ServerAlias entry from your provider. To use the htaccess file they have to first get to your web site and if www.domain.com is not redirecting there then they would never get to the point where they would access the file. Does that make sense?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.