配置Nginx使用Https的最简单方法

Published: Tags: LINUX NGINX

年初的时候笔者所在的公司就配置了JAVA和NGINX的SSL接入,然而最近有个朋友也需要把NGINX加上HTTPS, 但是网上配置太多让人眼花缭乱,因此为了不求甚解,笔者就以最简单的方式为NGINX加上HTTPS的访问协议啦~

以下是原始的Nginx默认接入配置:

server {
    listen       80;
    server_name  test.jtwo.me;

    root /data/www;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include        fastcgi_params;
        fastcgi_pass   127.0.0.1:9000;
    }

    location ~* \.(?!(php|jsp|asp|aspx)$) {
        add_header Cache-Control "max-age=31536000";
    }
}

然后,其实添加HTTPS只需要三行(同时修改443默认端口):

server {
    listen       443; # HTTPS
    server_name  test.jtwo.me;

    # 只需要增加以下三行配置
    ssl                  on;
    ssl_certificate      "/data/ssl/nginx.crt";
    ssl_certificate_key  "/data/ssl/nginx.key";

    root /data/www;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include        fastcgi_params;
        fastcgi_pass   127.0.0.1:9000;
    }

    location ~* \.(?!(php|jsp|asp|aspx)$) {
        add_header Cache-Control "max-age=31536000";
    }
}

看,就这么简单!ssl_certificate是CA颁发的证书,ssl_certificate_key是申请证书时的私钥。

####附加资料: * 免费SSL证书申请-腾讯云-免费一年 * 免费SSL证书申请-StartSSL-免费一年 * Nginx官方文档-Https模块说明(英文)