Kevin Sedgley
Kevin Sedgley

Reputation: 1069

Redirect www and http requests to https://, catching all domains, in nginx

In nginx, we wish to redirect all requests sent to:

https://www.<domain>
http://www.<domain>
http://<domain>

To:

https://<domain> 

ie SSL, without the www prefix, as a catch-all, without specifying each domain individually.

The config we have come up with nearly works:

server {
        server_name "~^www\.(.*)$" ;
        return 301 https://$1$request_uri ;
}

server {
        listen                  80 default;
        client_max_body_size    10m;
        client_body_buffer_size 128k;
        return                  301 https://$host$request_uri;
}

server {
        listen                  443;
        ssl                     on;
        ..... etc ......

...but the first server block (the www catch) seems to be matching all requests, and not just the ones that are www.*

Upvotes: 1

Views: 2380

Answers (1)

Valeriy Solovyov
Valeriy Solovyov

Reputation: 5648

nginx manual: A redirect to a main site

server {
    listen   80;
    listen   [::]:80;

    server_name www.example.com;

    return 301 https://example.com$request_uri;
}
server {
    listen   443 default_server ssl;

    server_name www.example.com example.org;

    ssl_certificate        /path/to/my/cert;
    ssl_certificate_key  /path/to/my/key;
}

don't lose “everything else”:

server {
    listen       80 default_server;
    server_name  _;
    return       301 http://example.com$request_uri;
}

more efficient, by only running the rewrite on the http protocol it avoids having to check the $scheme variable on every request (IfIsEvil)

Maybe you can try use in one place 80/443:

server {
    listen   80;
    listen   [::]:80;
    listen   443 default ssl;

    server_name www.example.com;

    ssl_certificate        /path/to/my/cert;
    ssl_certificate_key  /path/to/my/key;

    if ($ssl_protocol = "") {
       rewrite ^   https://$server_name$request_uri? permanent;
    }
}

Upvotes: 2

Related Questions