How to make a website accessible only via https and without www?

Is there a website https://example.com Want, sothat it was only through https and without www, in other cases must be redict 301 to the appropriate ulr https without www, that is:

example.com -> 301 -> https://example.com
https://www.example.com -> 301 -> https://example.com
https://www.example.com/something -> 301 -> https://example.com/something
www.example.com/something -> 301 -> https://example.com/something

etc.

With nginx are the settings that work partially:

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

server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name localhost example.com www.example.com;
#return 301 https://example.com$request_uri; -- why there was an infinite redirect
# .......


The site itself is running on the server on localhost:3000
July 8th 19 at 15:25
1 answer
July 8th 19 at 15:27
Solution
because you are the redirects themselves.

You need to do something like this:
server {
listen 80 ;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}

server {
listen 443 ssl ;
listen [::]:443 ssl ;
server_name localhost www.example.com;
return 301 https://example.com$request_uri;
}

server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name example.com


... here is the main config for your server
}
Logical `default_server` to write the second block, and not in the third. - annie_Pagac commented on July 8th 19 at 15:30
why? If you register in the second, will be redirect to third always? - giovanna.DuBuque commented on July 8th 19 at 15:33
: well, Yes. That's what you need - annie_Pagac commented on July 8th 19 at 15:36
: the default needs to open the website without www and 443. And this is the third configuration. If you register in the second, all cases not described will trigger a redirect to the third. - giovanna.DuBuque commented on July 8th 19 at 15:39
: It seems you misunderstand "default".

> in other cases should be redict 301
Ie if I enter any address except main, should be a redirect. - annie_Pagac commented on July 8th 19 at 15:42
: I understand: by default, if a request came to the server and not come to any server_name.

The word TC can be interpreted also in two ways. - giovanna.DuBuque commented on July 8th 19 at 15:45

Find more questions by tags Nginx