Problem with "no www" htaccess rule

I want to use the htaccess rule that ensures that anyone who types an address beginning with www gets redirected to mydomain.co.uk


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

…the usual kind of thing that seems to be in every htaccess guide that I’ve read so far. What they don’t mention is that it fails on a server that uses a public_html directory, so I get redirected to mydomain.co.uk/public_html/ and get a 404.

I found that adding a 301 from that directory to mydomain.co.uk fixed it, but I doubt whether that is really the best solution. Is there a proper fix that people use when they have to deal with these public_html directories?

I’m working through recreating my site on a new host’s server so I haven’t had to work with this weird directory structure before.

I’ve always found this to work nicely, and I have a public_html directory:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\\.(([a-z0-9_]+\\.)?mydomain\\.co.uk)$ [NC]
RewriteRule .? http://%1%{REQUEST_URI} [R=301,L]

I use that in a .htaccess file.

There’s some more great info here, which you might find more useful:

(Look about half way down the page.)

Sounds like something is happening “under the hood”. Most likely an Alias of sorts.

What happens if you put RewriteBase / in your code? (just after RewriteEngine On)

I have the rewritebase command in there.

I think that I might have fixed it myself, that is, if what I’ve done is OK to do (vis a vis my hosting provider). On a hunch, I moved my main htaccess file out of the uppermost part of the directory structure and into the public html directory. It’s not how the server was set up by the host, but the problem has been fixed. I have a deny files function in it, so it should be OK as far as I know.

Let me know if you think that any functions should be in the higher directory.

Thanks to both of you for your responses.

Yes it’s fine to have it there. I actually thought that’s where you had it already :slight_smile:

No, I just put my edited version back where the original was. Seemed a safe bet.

Thanks for replying.