首页 > 技术文章 > nginx常用配置系列-HTTPS配置

ieinstein 2017-06-27 09:46 原文

接上篇,nginx配置系列

HTTPS现在已经很流行,特别是AppStore上线的应用要求使用HTTPS进行通信,出于安全考虑也应该使用HTTPS,HTTPS配置需要准备证书文件,现在也有很多免费证书可以申请,比如阿里云

证书相关有两个文件,一个key文件server.key,一个证书文件server.crt(证书文件的格式有很多(pem,p12,crt等)一般使用pem或crt,nginx都支持)

直接看配置代码(example.com.conf文件)

server {
    # HTTPS 默认443端口
    listen 443 ssl;
    # 证书文件配置,指定证书的路径,除了证书路径其他配置都默认
    ssl_certificate     /usr/local/nginx/ssl/server.crt;
    ssl_certificate_key /usr/local/nginx/ssl/server.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5:!DH;
    
    # host
    server_name example.com www.example.com;
    
    #设置长连接
    keepalive_timeout 70;    
    #减少点击劫持
    add_header X-Frame-Options DENY;
    #禁止服务器自动解析资源类型
    add_header X-Content-Type-Options nosniff;
    #防XSS攻击
    add_header X-Xss-Protection 1;
    
    # 默认index
    index index.html index.htm index.php default.html default.htm default.php;
    # 代码的根目录
    root  /home/wwwroot/example;
    # 访问日志
    access_log  /home/wwwlogs/example.com.log  main;
    
    # 文件的规则(详见http://seanlook.com/2015/05/17/nginx-location-rewrite/index.html)
    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
        expires      30d;
    }
    location ~ .*\.(js|css)?$ {
        expires      12h;
    }
}

# 全站使用HTTPS,让通过HTTP访问的用户301跳转到HTTPS
server {
    listen      80;
    server_name example.com www.example.com;
    #使用return的效率会更高
    return 301 https://$server_name$request_uri;
}

这个配置最需要关注的就是证书文件的配置,再就是HTTPS的端口默认是443,如果全站使用HTTPS的话,需要让80端口的HTTP请求跳转到HTTPS请求即可

============= nginx HTTPS 配置完毕 ==============

 

文中有不足指出请直接指出,一起学习讨论,QQ:1485619676

推荐阅读