I've been looking over the same .htaccess codes that will not work for a subdomain. It seems not many people really know how to do a correct .htaccess (including me I suppose). I've tried:

RewriteCond %{HTTP_HOST} !^site\.net$ [NC]
RewriteRule ^(.*)$ http://site.net/$1 [R=301,L]

And it requires the WWW on the subdomain, such as , which I do not want. Does anyone have a solution to my problem?

Dani AI

Generated

Short answer: the original rule used a “not” match, so any host that wasn’t exactly the bare domain (including subdomains) triggered the redirect. As discovered, the correct approach is to match the apex host exactly. The examples below show a safer, production-ready way to force www for only the apex domain while leaving subdomains (bob.example.com, etc.) alone.

# only redirect the exact apex host to the www canonical host (modern Apache)
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ %{REQUEST_SCHEME}://www.example.com%{REQUEST_URI} [R=301,L]

For older Apache versions that lack %{REQUEST_SCHEME}, handle HTTP/HTTPS explicitly:

# Apache <2.4: explicit http/https handling
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} =on
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

Notes and troubleshooting: place these lines at the top of the .htaccess (or, better, in the VirtualHost) so they run before other rewrites. Ensure mod_rewrite is enabled and AllowOverride permits .htaccess rewrites. Test with a temporary redirect (302) first to avoid browser caching and then switch to 301 when confirmed. Use a tool like curl -I to verify the Location header and to catch redirect loops. If the server uses a catch‑all vhost for many subdomains, ensure the rule lives only in the document root intended for the apex host so it won’t accidentally run for other vhosts.

Recommended Answers

All 2 Replies

So, basically starting off reading your rule, it says:
If someone accesses this site that is *NOT* from http://site.net
Then redirect them to http://site.net/string

Maybe removing the 'NOT' is what your looking for:

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

Which would state, if someone is accessing your site from site.net redirect to www.site.net/string

This rule would activate for anyone hitting http://site.net but not

Is this the goal?

Yes, that worked. Thanks mate! Its so difficult finding any good information about htaccess. It seems no one really knows it well enough.

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.