Reputation: 528
If the main domain is: example.com
I have a rule that forces a www sub-domain.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
But, I only want to redirect {blank} to www.
If there's a 123.example.com
, I don't want to respond.
If there's a wibble.example.com
, I don't want to respond.
If there's a shop.example.com
, I don't want to respond.
So example.com
should go to www.example.com
All other will get the 'site not found' message.
Can I do this in .htaccess
?
Upvotes: 1
Views: 78
Reputation: 133600
With your shown samples, please try following. Please make sure my newly added rule is at the top of your .htaccess file.
Also please do clear your browser cache before testing your URLs.
RewriteEngine ON
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^ - [F,L]
Upvotes: 3
Reputation: 42935
You cannot somehow trigger the message "site not found" in a client by a configuration in your http server. That message is shown if the name resolution for a host name (sometimes called a "subdomain") does not work. That is a DNS detail which has nothing to do with configuring your http service. You will have to take care to set the correct DNS entries for that.
If there is a DNS resolution for those subdomains which points to your http server's address, then your server will respond. You cannot somehow configure the server not to respond to an incoming request. That is out of scope for an http server.
The first defined host inside your http server will be chosen in that case, it acts as a default or fallback host. So all you can do is block incoming requests to such hosts. For that, why don't you turn around your logic, that should be much easier to understand:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,END]
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^ - [F,END]
Upvotes: 1