第一步,将 @ 根域名,解析到与 www 为公一个服务器 IP
第二步,修改服务部署,添加跟域名
version: '3.1'
services:
server:
....
environment:
VIRTUAL_HOST: example.com, www.example.com
VIRTUAL_PORT: 8080
LETSENCRYPT_HOST: example.com, www.example.com
......
❯ curl -I http://example.com
HTTP/1.1 301 Moved Permanently
Content-Length: 169
Content-Type: text/html
Date: Thu, 02 Nov 2023 02:03:49 GMT
Location: https://example.com/
Server: nginx/1.21.4
❯ curl -I https://example.com
HTTP/2 200
server: nginx/1.21.4
date: Thu, 02 Nov 2023 02:03:56 GMT
content-type: text/html; charset=utf-8
content-length: 64025
x-powered-by: Express
cache-control: public, max-age=0
etag: W/"fa19-6y7vfdU9YnEXWxUatndF22dWJsM"
vary: Accept-Encoding
strict-transport-security: max-age=31536000
根域名能正常使用,我们需要将它转到 www.example.com 而不是直接响应,需要覆盖 example.com 的 location 配置。
看看 nginx-proxy 的配置映射目录
volumes:
- ./certs:/etc/nginx/certs:ro
- ./conf.d:/etc/nginx/conf.d
- ./vhost.d:/etc/nginx/vhost.d
- ./html:/usr/share/nginx/html
- ./htpasswd:/etc/nginx/htpasswd
需要再 vhost.d 中创建 `example.com_location_override` 文件。文件内容如下
location / {
return 301 https://www.example.com$request_uri;
}
最后重启一下 nginx-proxy
docker restart nginx-proxy
检测结果
❯ curl -I https://example.com
HTTP/2 301
server: nginx/1.23.4
date: Thu, 02 Nov 2023 03:17:53 GMT
content-type: text/html
content-length: 169
location: https://www.example.com/
strict-transport-security: max-age=31536000
完成