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:
source share