温馨提示×

ubuntu thinkphp如何配置ssl

小樊
43
2026-10-13 10:26:55
栏目: 云计算

在 Ubuntu + ThinkPHP 环境下配置 SSL,通常有两种常见做法:

  1. 在 Web 服务器(Nginx / Apache)上配置 SSL(✅ 推荐,最标准)
  2. ThinkPHP 自身仅做强制 HTTPS 跳转

下面以 Ubuntu + Nginx + ThinkPHP(5.x / 6.x / 8.x 通用) 为例说明。


一、准备 SSL 证书

1️⃣ 使用 Let’s Encrypt(免费,推荐)

sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

证书位置(自动生成):

/etc/letsencrypt/live/yourdomain.com/fullchain.pem
/etc/letsencrypt/live/yourdomain.com/privkey.pem

二、Nginx 配置 SSL(关键)

示例 Nginx 配置

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;

    root /var/www/html/thinkphp/public;
    index index.php index.html;

    ssl_certificate     /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

⚠️ PHP 版本按你服务器实际修改(如 php8.2-fpm)


三、ThinkPHP 中配置 HTTPS

1️⃣ 强制 HTTPS(推荐)

编辑:

config/app.php
'https' => true,

或中间件方式(ThinkPHP 6/8):

// app/middleware.php
return [
    \think\middleware\CheckHost::class,
];

2️⃣ URL 生成带 https

'url_domain_root' => 'https://yourdomain.com',

四、Apache 用户(简要)

启用 SSL

sudo a2enmod ssl
sudo a2ensite default-ssl

修改

SSLCertificateFile      /etc/letsencrypt/live/yourdomain.com/fullchain.pem
SSLCertificateKeyFile   /etc/letsencrypt/live/yourdomain.com/privkey.pem

五、常见问题

❌ 页面还是 http

  • 清浏览器缓存
  • 检查 Nginx 是否 return 301
  • 检查 CDN(如 Cloudflare)

❌ 后台资源还是 http

  • 使用 __URL__ / asset()
  • 不要写死 http://

六、总结(最简流程)

申请证书 → Nginx 配 443 → 301 跳转 → ThinkPHP 开 https

如果你用的是 ThinkPHP 版本 / Nginx or Apache / 是否用宝塔,我可以给你更精确配置。

0 踩