13

I'm trying to redirect all subdomains to my main domain, but so far it isn't working. Here's how I'm doing it:

server { listen [::]:80; server_name *.example.com; return 301 $scheme://example.com$request_uri; } server { listen [::]:443; server_name example.com; ssl on; ssl_certificate /etc/ssl/certs/example.com.crt; ssl_certificate_key /etc/ssl/private/example.com.key; #enables all versions of TLS, but not SSLv2 or 3 which are weak and now deprecated. ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #Disables all weak ciphers ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECD$ ssl_prefer_server_ciphers on; root /var/www/html; index index.html; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules } } 

However, when I type e.g. www.example.com it redirects to https://www.example.com, how can I redirect all sub-domains to https://example.com?

2 Answers 2

13

If you have multiple sites on same server and one of your main sites would be www.example.com:

# main domain: server { listen 80; server_name www.example.com; ... } 

For all sub domains, bads or misspelled can be redirected to www:

server { listen 80; server_name *.example.com; return 301 http://www.example.com; } 

Nginx will check first www.example.com and if not matched all what ever other subdomains will be redirected to www one.

Sign up to request clarification or add additional context in comments.

1 Comment

fastcgi_script_name?
4

You can simply create a default server, that redirects everything to https://example.com like this:

server { listen [::]:80 default_server; server_name localhost; return 301 https://example.com$request_uri; } 

All incoming requests, that don’t find a matching server will be served by the default server, which will redirect them to the correct domain.

1 Comment

but the same server can have several different domains and webpages, and the OP just asked to redirect everything from *.example.com to example.com

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.