2020-06-27 20:55:17
要让PHP框架支持HTTPS访问,需完成SSL证书部署、HTTP到HTTPS跳转配置及框架内HTTPS参数设置。以下是分步骤的详细说明:
一、申请并部署SSL证书获取证书
从云服务商(阿里云、腾讯云)申请免费DV证书,或使用Let's Encrypt自动生成。
证书文件通常包含.crt(公钥)和.key(私钥),部分服务商提供组合文件(如fullchain.pem)。
上传证书到服务器
将证书文件上传至服务器指定目录,例如Nginx默认路径:/etc/nginx/ssl/
配置Nginx支持HTTPS修改Nginx站点配置文件(如/etc/nginx/sites-available/yourdomain.com),添加以下内容:
server { listen 443 ssl; server_name yourdomain.com; ssl_certificate /etc/nginx/ssl/fullchain.pem; # 证书路径 ssl_certificate_key /etc/nginx/ssl/private.key; # 私钥路径 ssl_protocols TLSv1.2 TLSv1.3; # 启用安全协议 ssl_ciphers HIGH:!aNULL:!MD5; # 加密套件 root /var/www/html/public; # PHP框架入口目录 index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ .php$ { fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }}重启Nginx生效:systemctl reload nginx
Apache服务器配置若使用Apache,需在虚拟主机配置中启用SSL模块并指定证书路径:
<VirtualHost *:443> ServerName yourdomain.com SSLEngine on SSLCertificateFile /path/to/cert.pem SSLCertificateKeyFile /path/to/private.key DocumentRoot /var/www/html/public</VirtualHost>启用SSL模块:a2enmod sslsystemctl restart apache2
Nginx强制跳转在Nginx配置中添加80端口的重定向规则:
server { listen 80; server_name yourdomain.com; return 301 https://$host$request_uri; # 永久重定向}Apache强制跳转启用rewrite模块后,在.htaccess或虚拟主机配置中添加:
RewriteEngine OnRewriteCond %{HTTPS} offRewriteRule ^(.*)$不同框架需手动设置HTTPS参数,避免生成URL时仍使用HTTP。
Laravel框架
方法1:在AppServiceProvider的boot方法中强制设置HTTPS:if ($this->app->environment('production')) { $this->app['request']->server->set('HTTPS', true);}
方法2:修改config/app.php,设置默认URL为HTTPS:'url' => '
ThinkPHP框架在config.php中启用HTTPS模式:
'url_https' => true,Symfony框架在.env文件中配置信任代理和主机:
TRUSTED_PROXIES=127.0.0.1TRUSTED_HOSTS=yourdomain.com访问测试
直接访问
检查地址栏是否显示锁图标(