Remove www. on behalf of the host using Nginx Rewrite

I am trying to configure my Nginx to highlight www. from the host name. I am looking for a general rule that handles possible cases of subdomains.

eg. If http://www.foo1.sample.com and http://www.fooX2.sample.com are two areas.

Then I want to delete any www. in front of such subdomains and redirect them to http://foo1.sample.com and http://fooX2.sample.com respectively (WITHOUT the VALUE of the EXACT subdomain in the rule.)

Thanks.

+6
source share
2 answers

I think adding the following if the block in your Nginx conf file should work for you. It also takes care of the case of the subdomain you mentioned.

 if ($host ~* ^www\.(.*)) { set $host_without_www $1; rewrite ^(.*) http://$host_without_www$1 permanent; } 
+11
source

Best practice:

The best practice, as well as the most efficient way, would be to use a separate server definition for this.

This will not only ensure that the configuration is automatically applied to all websites hosted on your nginx instance, but also ensures that you will not run regular expressions for the hostname from multiple instances in your code.

The following is the simplest form:

 server { listen 80; server_name ~^www\.(?<domain>.+)$; return 301 $scheme://$domain$request_uri; } 

If you use https , then things get complicated because you have to make sure the certificates don't match. If you do not have a single certificate for all your domains, it’s best to just hardcode everything, as it is already hardcoded in the certificate anyway, and a solution like the one described above is simply not possible because of the certificate requirements.


Alternative:

Please note that another answer to the question that uses rewrite ^(.*) http://…$1 … is incorrect and will lead to the loss of $query_string , as well as to potential manipulation of request encoding according to Nginx pass_proxy subdirectory without URL decoding .

If you need an if -based approach and no hard coding, none of which is recommended, for example, like the other answer, at least use the correct paradigm to avoid bloating and losing $query_string ; note that according to the regular expression of the nginx server name, when the "Host" header has an endpoint , the $host variable is already normalized with nginx (the endpoint is deleted, everything is lowercase), so you don’t have to worry about doing the comparison without case, as in another answer:

 if ($host ~ ^www\.(?<domain>.+)$) { return 301 $scheme://$domain$request_uri; } 

Recommendations:

0
source

All Articles