Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

ssl - NGINX Redirect http to https and non-www to ww

I'm setting up an nginx server with an SSL.

The domain with the ssl is www.mydomain.com

I want to redirect all requests from:

http://mydomain.com, http://www.mydomain.com, & https://mydomain.com to

https://www.mydomain.com

I have the following server blocks setup currently:

server{
  listen 443 ssl;
  root /www/mydomain.com/;

  ssl_certificate /ssl/domain.crt;
  ssl_certificate /ssl/domain.key;
  .
  . 
  .
}

server{
  listen 80;
  server_name mydomain.com;
  return 301 https://www.mydomain.com$request_uri;
}

server{
  listen 80;
  server_name www.mydomain.com;
  return 301 https://www.mydomain.com$request_uri;
}

server{
  listen ssl 443;
  server_name mydomain.com;
  return 301 https://www.mydomain.com$request_uri;
}

This currently does not work, but I don't understand why not. I can get a combination of either http -> https working or no-www to -> www working, but mixing them as above does not work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ssl redirect won't work if your ssl certificate doesn't support the non-www domain. The config is correct but can be reduced to just 1 redirect server

Also don't forget to reload nginx sudo service nginx reload

server {
  listen 80;
  listen 443 ssl;
  server_name example.com;
  # add ssl settings
  return 301 https://www.example.com$request_uri;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...