I do have an nginx server which responds to several domains and I do want to redirect all request to the main domain.
Example: website responding for xxx xxx.example.com yyy.example.com $hostname
for both http
and https
.
I want to configure the server in such way that all requests to the other domain names will be redirected to xxx.example.com
.
Most efficient and clean way to do this is to configure two separate server{} blocks - one to do redirects, and another one (with canonical name) to actually handle requests.
Example configuration:
Documentation:
I thinks something along these lines should work:
Here's a variant on Brenton Alker's anser, using the
$server_name
variable to reuse the value of theserver_name
directive.Or, to keep any query parameters:
Here,
$server_name
refers to primary server name, which is the first name in theserver_name
directive, while$host
refers to the hostname given in the HTTP request.Note that the
if
statement in nginx configuration does not always do what you would expect and its use is discouraged by some. See also https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/