Nginx给WordPress无感知地加上HTTPS
序言
搭建WordPress,开始写文章后,就要解决浏览器左上角的「不安全」提示了。
虽然HTTP方便迁移,但是在稳定安全的运维中,HTTPS是必不可少的。 刚刚给站点加上HTTPS,做个笔记吧。
原理
用 Nginx 反向代理的方法将 HTTP流量 代理成 HTTPS流量 ,WordPress 无需配置。
准备工作
- WordPress正运行在docker里面。
Certbot
申请了一份 公钥 和 私钥。
步骤
本实验用 enix223/awesome-nginx:alpine
做 nginx 镜像,它已经集成了 H5BP(HTTPS) 模块。编写 conf 很方便。
1. 准备目录
在自己喜欢的目录里面,新建 ssl
和 conf
目录。
2. 编写 docker-compose.yaml
# docker-compose.yaml 文件
version: '3'
services:
# Nginx 服务名称,可以随便改
nginx:
# 这里用封装好的 Nginx 镜像
image: enix223/awesome-nginx:alpine
# 指定容器名字可以方便进入容器,可以随便改
container_name: nginx
# 指定主机网络后,不需要映射端口
network_mode: 'host'
# 目录映射
volumes:
- './ssl:/lib/ssl:ro' # 证书
- './conf:/lib/conf/:ro' # Nginx 配置文件
# 强制指定程序入口为 shell
entrypoint: '/bin/sh'
# 和入口一起,组装后的指令是: /bin/sh -c '复制配置文件 然后 启动 Nginx'
command:
- '-c'
- "cp lib/conf/*.conf /etc/nginx/conf.d/ && nginx -g 'daemon off;'"
# 容器挂掉时自动重启
restart: always
3. 编写 nginx 配置文件
在 conf
下新建 example.net.conf
文件
# 服务器块
server {
# 监听 443
listen [::]:443 ssl http2;
listen 443 ssl http2;
# 启动 SSL 引擎
include h5bp/ssl/ssl_engine.conf;
# 服务器名
server_name example.net;
# 指定证书地址(容器内的路径)
# 公钥
ssl_certificate /lib/ssl/example.net.pem;
# 私钥
ssl_certificate_key /lib/ssl/example.net.key;
# 当访问服务器根目录时
location / {
# 转发至 HTTP 服务器
proxy_pass http://127.0.0.1:80/;
# [这个很重要!] 关闭重定向
proxy_redirect off;
# 设置头部,建议加上
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
add_header X-Frame-Options SAMEORIGIN;
}
# H5BP 已经封装好必要的SSL配置,只需要 include 一下即可
include h5bp/ssl/policy_intermediate.conf;
include h5bp/basic.conf;
include h5bp/errors/custom_errors.conf;
include h5bp/security/strict-transport-security.conf;
}
4. docker-compose 启动
容器直接启动,CTRL+C会结束掉
docker-compose up
让容器在后台启动
docker-compose up -d
总结
当时就有类似的想法,但是实践之后出现 Apache 无限重定向,后来参考了文章后发现是少了 proxy_redirect off;