variable for domain name in redirect

Maxim Dounin mdounin at
Sun Jul 1 15:17:55 UTC 2018


On Sun, Jul 01, 2018 at 03:52:59AM -0400, shiz wrote:

> I have something in one of my server bloc:


>   if ($rule_9 = "3210"){
>     return 301$request_uri;
>   }
> ```
> The problem is that have several servers.
> 1 - Is there a way to use variable for the some server names in the 'return
> 301' line so I could use shared code and not have to edit this snippet
> everywhere another site turns https?
> 2 - I have a lot of those return 301 where code could be shared if something
> like this were available e.g.
> $scheme://$actual_real_server_name$request_uri
> Difficulty,  the server_name can and often contains multiple entries.
> I have found nothing useful about this on serverfault nor anywhere else. 
> Dealing with this for several years.

In most cases, $server_name is the variable you want.  This 
variable contains the name of the server as defined by the 
server_name directive, see$server_name.  If 
there are multiple names defined, it will contain the first one.

In some cases, you may also want to use the $host variable.  It 
will contain the name as obtained from the client, and might be 
better than $server_name if a single server{} block is used to 
handle requests to multiple different names and you don't want 
nginx to return redirects to a canonical name, but prefere to keep 
names separate.

Maxim Dounin

More information about the nginx mailing list