You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为同IP不同端口的Yii2项目前后端配置Apache SSL?

同一IP、不同端口的Yii2前后端Apache SSL配置方案

你当前配置的核心问题是VirtualHost端口分配错误以及ServerName写法不符合Apache规则,以下是修正后的完整配置步骤:

1. 配置Apache监听端口

先确保Apache监听所有需要的端口,编辑/etc/httpd/conf/httpd.conf(或独立的ports.conf文件),添加以下指令:

Listen 80
Listen 8080
Listen 443
Listen 8443

2. 修正SSL VirtualHost配置(ssl.conf)

后端SSL服务需使用独立端口(如8443),不能和前端共用443端口;同时ServerName仅写域名,不要带端口号:

# 前端HTTPS配置(443端口)
<VirtualHost 192.168.12.125:443>
    ServerName test.mydomain.co.tz
    DocumentRoot /var/www/html/tan_web/frontend/web
    SSLEngine on
    SSLCertificateFile /var/www/html/tan_web/sslDocs/mail_tanesco_co_tz.crt
    SSLCertificateKeyFile /var/www/html/tan_web/sslDocs/test_tanesco_co_tz.key
    SSLCertificateChainFile /var/www/html/tan_web/sslDocs/DigiCertCA.crt

    # 开启Yii2 URL重写权限
    <Directory "/var/www/html/tan_web/frontend/web">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

# 后端HTTPS配置(8443端口)
<VirtualHost 192.168.12.125:8443>
    ServerName test.mydomain.co.tz
    DocumentRoot /var/www/html/tan_web/backend/web
    SSLEngine on
    SSLCertificateFile /var/www/html/tan_web/sslDocs/mail_tanesco_co_tz.crt
    SSLCertificateKeyFile /var/www/html/tan_web/sslDocs/test_tanesco_co_tz.key
    SSLCertificateChainFile /var/www/html/tan_web/sslDocs/DigiCertCA.crt

    # 开启Yii2 URL重写权限
    <Directory "/var/www/html/tan_web/backend/web">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

3. 修正HTTP跳转配置(httpd.conf)

ServerName同样不要带端口,跳转目标对应正确的HTTPS端口:

# 前端HTTP自动跳转HTTPS
<VirtualHost 192.168.12.125:80>
    ServerName test.mydomain.co.tz
    DocumentRoot /var/www/html/tan_web/frontend/web
    Redirect permanent / https://test.mydomain.co.tz/
</VirtualHost>

# 后端HTTP自动跳转HTTPS
<VirtualHost 192.168.12.125:8080>
    ServerName test.mydomain.co.tz
    DocumentRoot /var/www/html/tan_web/backend/web
    Redirect permanent / https://test.mydomain.co.tz:8443/
</VirtualHost>

4. 配置Yii2的.htaccess文件

分别在前后端的web目录下创建/修改.htaccess文件,确保URL重写正常:

RewriteEngine on

# 真实存在的文件/目录直接访问
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 其他请求转发到index.php
RewriteRule . index.php

5. 验证配置并重启服务

执行命令检查配置语法:

apachectl configtest

若显示Syntax OK,重启Apache服务:

systemctl restart httpd

测试访问

  • 前端:访问http://test.mydomain.co.tz会自动跳转到https://test.mydomain.co.tz
  • 后端:访问http://test.mydomain.co.tz:8080会自动跳转到https://test.mydomain.co.tz:8443

内容的提问来源于stack exchange,提问作者Roman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 22:22:53