0

How to redirect every vhost to https but without duplicating configuration. I have 4 websites on the same vps running Nginx and I want to redirect everything to https.

2
  • Each redirect needs the site name, so you have to duplicate at least some of the config. You can use include for some parts.
    – Tim
    Oct 25, 2017 at 23:41
  • not true @Tim see answer Oct 25, 2017 at 23:41

1 Answer 1

2

Like this...

Redirect ALL requests to https In catch-all server examples the strange name “_” can be seen

server {
        listen 80;
        listen [::]:80;
        server_name _;
        access_log /var/log/nginx/www-301_access.log;
        error_log /var/log/nginx/www-301_error.log;

        location / {
                return 301 https://$host$request_uri;
        }
}

Redirect specific domain names

server {
        listen 80;
        listen [::]:80;
        server_name example.com *.example.com example.org *.example.org;
        access_log /var/log/nginx/www-301_access.log;
        error_log /var/log/nginx/www-301_error.log;

        location / {
                return 301 https://$host$request_uri;
        }
}
6
  • Similar answer serverfault.com/a/547748/200560 Oct 25, 2017 at 23:42
  • I prefer not to use the default server for this. I return an error status code so that only requests for configured domains are serviced. This is a solution, and there's nothing wrong with it, but it's not one I'd use personally.
    – Tim
    Oct 26, 2017 at 0:03
  • Oh I agree, I 444 anyone hitting things like the IP Address directly, etc. Oct 26, 2017 at 0:05
  • What is this underscore in server name ? Oct 26, 2017 at 0:06
  • catch all, see nginx.org/en/docs/http/server_names.html Oct 26, 2017 at 0:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.