合并两个Nginx服务器

时间:2018-12-28 08:54:19

标签: http nginx https webserver nginx-config

此nginx配置应该重定向

http://example.com
http://www.example.com
https://www.example.com

https://example.com

server {
  server_name example.com;
  root {:siteRoot};  
  listen 443 ssl;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  include /etc/letsencrypt/options-ssl-nginx.conf;
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
  index index.html;
}

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

server {
  server_name www.example.com;
  listen 443 ssl;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  include /etc/letsencrypt/options-ssl-nginx.conf;
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
  return 301 https://example.com$request_uri;
}

它工作正常,但是可以通过某种方式合并以避免所有重复的代码吗?

1 个答案:

答案 0 :(得分:2)

server {
  server_name www.example.com example.com;
  root {:siteRoot};  
  listen 443 ssl;
  listen 80;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  include /etc/letsencrypt/options-ssl-nginx.conf;
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

  if ($scheme = http) {
  return 301 https://example.com$request_uri;
  }

  if ($host = 'www.example.com') {
  return 301 https://example.com$request_uri;
  }
    index index.html;

}

正如我评论的那样,我喜欢在服务器中将我在nginx中的不同选项分开,因为我认为它不是“代码”。但是我想,如果您想将所有内容都放在同一台服务器上,那么我刚刚写的内容应该对您有用。我正在设置一个虚拟服务器,以检查“ ifs”书面工作是否按预期进行,因为这个概念是正确的,但我需要深入检查代码。