How to configure nginx to redirect all request from domain aliases to main domain?
Solution 1
I thinks something along these lines should work:
set $primary_domain "xxx.example.com";
if ($host != $primary_domain) {
rewrite ^ $scheme://$primary_domain permanent;
}
Solution 2
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:
server {
listen 80;
listen 443 ssl;
server_name xxx yyy.example.com $hostname;
ssl_certificate ...
ssl_certificate_key ...
return 302 $scheme://xxx.example.com$request_uri;
}
server {
listen 80;
listen 443 ssl;
server_name xxx.example.com;
ssl_certificate ...
ssl_certificate_key ...
...
}
Documentation:
Solution 3
Here's a variant on Brenton Alker's anser, using the $server_name
variable to reuse the value of the server_name
directive.
server_name primary.tld secondary.tld;
if ($host != $server_name) {
rewrite ^ $scheme://$server_name permanent;
}
Or, to keep any query parameters:
server_name primary.tld secondary.tld;
if ($host != $server_name) {
rewrite ^/(.*) $scheme://$server_name/$1 permanent;
}
Here, $server_name
refers to primary server name, which is the first name in the server_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/
Related videos on Youtube
sorin
Another geek still trying to decipher the meaning of “42”. It seems that amount his main interest are: online communities of practice and the way they evolve in time product design, simplicity in design and accessibility productivity and the way the IT solutions are impacting it
Updated on September 18, 2022Comments
-
sorin over 1 year
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 bothhttp
andhttps
.I want to configure the server in such way that all requests to the other domain names will be redirected to
xxx.example.com
. -
VBart over 11 yearsThis is the worst way to solve the problem. wiki.nginx.org/Pitfalls#Server_Name and nginx.org/en/docs/http/converting_rewrite_rules.html
-
inspirednz about 6 yearsMarking down for the reasons already stated by VBart. In my opinion this should not be the correct answer.