返回首页 - Notes - 2016

给 NGINX 站点配置 HTTPS


基本配置

NGINX + WordPress 站点为例,这里假定站点的访问地址为 www.sample.com

  1. 先正常设置好站点的 NGINX 配置,确保站点可以正常访问
    upstream sample_com_list {
      ip_hash;
      server unix:/var/run/php5-fpm.sock weight=1 max_fails=1 fail_timeout=10;
    }
    
    server {
      listen       80;
      server_name  sample.com www.sample.com;
      root         /var/www/sample.com/current;
    
      access_log   /var/log/nginx/sample.com.access.log;
      error_log    /var/log/nginx/sample.com.error.log;
    
      location / {
        index     index.html index.php;
        try_files $uri $uri/ /index.php?$args;
      }
    
      location ~ \.php$ {
        fastcgi_pass   sample_com_list;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
      }
    }
    
  2. 安装 certbot
    wget -c https://dl.eff.org/certbot-auto
    chmod a+x certbot-auto
    sudo mv certbot-auto /usr/local/bin/certbot
    
  3. 创建一个目录存储生成的证书文件
    sudo mkdir -p /var/www/letsencrypt
    
  4. 修改 NGINX 配置让 certbot 能够验证域名所有权
    server {
      ...
      location ^~ /.well-known { root /var/www/letsencrypt; }
      ...
    }
    
  5. 重启 NGINX 使配置生效
    sudo nginx -s reload
    
  6. 生成证书
    sudo certbot certonly -a webroot -w /var/www/letsencrypt -d www.sample.com -d sample.com
    
  7. 修改 NGINX 配置文件,添加 HTTPS 配置信息
    upstream sample_com_list {
      ip_hash;
      server unix:/var/run/php5-fpm.sock weight=1 max_fails=1 fail_timeout=10;
    }
    
    server {
      listen       80;
      server_name  sample.com www.sample.com;
      return       301 https://$host$request_uri;
    }
    
    server {
      listen 443 ssl;
    
      server_name  sample.com www.sample.com;
      root         /var/www/sample.com/current;
    
      ssl_certificate /etc/letsencrypt/live/www.sample.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/www.sample.com/privkey.pem;
    
      access_log   /var/log/nginx/sample.com.access.log;
      error_log    /var/log/nginx/sample.com.error.log;
    
      location / {
        index     index.html index.php;
        try_files $uri $uri/ /index.php?$args;
      }
    
      location ~ \.php$ {
        fastcgi_pass   sample_com_list;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
      }
    }
    
  8. 重启 NGINX 使配置生效
    sudo nginx -s reload
    

完工,Over


证书续期

申请的免费证书只有三个月有效期,续期命令为:certbot renew

续期时需确保站点没有设置为自动跳转 HTTPS,能访问到 http://www.sample.com/.well-known


date:2016-11-23、2016-12-20、2017-02-21