My code doesn't work with second level tld's like domain.co.uk
Here is my conf:
# add www.
if ($host ~ ^(?!www)) {
rewrite ^/(.*)$ http://www.$host/$1 permanent;
}
# remove subdomain
if ($host ~ "^www\.(.*)\.(.*\.([a-z]{2,4}|[a-z]{2}\.[a-z]{2}))") {
set $host_without_sub $2;
rewrite ^/(.*)$ http://www.$host_without_sub/$1 permanent;
}
Your original configuration is not taking advantage of the nginx configuration. With a rewrite like that nginx will have to do extensive parsing on each request. If you are in an environment where performance and quick response time is essential then you'll want to use server blocks.
This way there is no complex parsing, Nginx uses a hash table for the server lookups and the rewrite uses the already parsed $request_uri variable.
I'm not sure why you have two versions. Here's what I have in my config. it removes
www.
from the start of any domain:This worked for me: