L
L
lexjusto2017-11-10 07:34:26
Nginx
lexjusto, 2017-11-10 07:34:26

How to set up redirect from www to non-www + HTTPS in Nginx?

Hello, before using HTTPS, I used the following design for redirecting from www to a non-www domain in the Nginx main config:

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

But now I have added HTTPS to my domain and found that it does not work as it should.
Specifically, then:
From www.domain.com redirects correctly to domain.com (HTTP)
But from http s ://www.domain.com does NOT redirect to https://domain.com (HTTPS)
How to do this in main nginx config without affecting localhosts?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lexjusto, 2017-11-10
@lexjusto

Thanks to all. I came to the right decision myself. I share with you:

server {
    server_name www.example.com example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;

    ssl_certificate /path/to/server.cert;
    ssl_certificate_key /path/to/server.key;

    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /path/to/server.cert;
    ssl_certificate_key /path/to/server.key;
    server_name example.com;

    <все локации основного домена>
}

M
metajiji, 2017-11-10
@metajiji

You need to make 2 servers for http and for https separately, you need to set listen in the https server, configure certificates ... After all, in order for the client to receive a 301 code, he needs to send a request to the server, your server does not listen on https :)
And more i would recommend using so called named regexps instead of $1

A
Andrey, 2017-11-10
@VELIK505

What's the habit of spawning server sections? What is the grandfather method? Everything is beautifully done in one section.

server {
  server_name mysite.com;
  root /var/www/user/data/www/mysite.com;
        index index.php;
    try_files  $uri $uri/ @rewrite;
  listen 123.456.789.11;
  listen 123.456.789.11 ssl http2;
  charset UTF-8;
.....
  set $root_path /.......;
        ssl_certificate /......;
        ssl_certificate_key /......;
      ......
.....
..........
        add_header Strict-Transport-Security "max-age=31536000";
.....
......
if ($scheme = http) {
rewrite ^ https://$http_host$request_uri? permanent;
}
if ($http_host !~ "^mysite.com$"){
rewrite ^(.*)$ https://mysite.com$1 redirect;
}
......
.....
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question