How to configure nginx to redirect all request from domain aliases to main domain?
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
.
I thinks something along these lines should work:
set $primary_domain "xxx.example.com";
if ($host != $primary_domain) {
rewrite ^ $scheme://$primary_domain permanent;
}
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:
- http://nginx.org/r/server_name
- http://nginx.org/r/return