LNMP环境下正确配置HTTP强制跳转HTTPS的方法

概述

一般来说,给站点申请了安全证书以后,都会希望访问者强制使用HTTPS来进行连接。HTTP强制跳转HTTPS通常有两种方法,一种是对整个域名使用正则表达式来进行rewrite重写,另外一种是通过301跳转来处理。Nginx官方并不推荐前者,其原文如下:

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites
# 不好的方法:
  rewrite ^/(.*)$ http://example.com/$1 permanent;
# 好的方法:
  rewrite ^ http://example.com$request_uri? permanent;
# 更好的方法:
  return 301 http://example.com$request_uri;

因此,对于HTTP强制跳转HTTPS的语句,应当写成:

return 301 https://$server_name$request_uri;

默认配置

对于自己手动编译安装的Nginx,其默认配置文件nginx.conf 将80端口和443端口(默认被注释)的监听分别写进了两个server段中,这是一种非常符合生产环境的标准做法。因此,只需要将上述语句直接复制到80端口对应的server段中,同时将该段中的location配置全部复制到443端口对应的server段中即可。类似如下:

# https部分
server
    {
        listen 443 ssl;
        server_name yourname.com;

        ssl_certificate      /dir/xx.crt;
        ssl_certificate_key  /dir/xx.key;
        ssl_dhparam          /dir/dhparam.pem;

        ssl_session_timeout  5m;

        ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers   on;
        ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+EXP;

        location / {
            root   /your/wwwroot/;
            index  index.html index.htm index.jsp index.do;
        }
    }

# http部分
server {
        listen 80;
        server_name yourname.com;
        return 301 https://$server_name$request_uri;
        location / {
            root /your/wwwroot/;
            index index.html index.htm index.jsp index.do;
        }
        # http部分的location字段可保留可删除
    }

作者: Hugh

Welcome to Wan's world~