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

如何通过Apache2或.htaccess实现多路径访问同一PHP应用?

解决方案对比与实现

方案选择逻辑

  • 若拥有服务器Apache主配置权限,优先使用Apache主配置文件方案:性能更优(无需每次请求读取.htaccess)、安全性更高(可关闭目录级的配置重载)、配置更灵活。
  • 若仅能操作站点目录(如共享主机),则使用**.htaccess + mod_rewrite方案**:无需修改服务器全局配置,适配受限环境。

一、Apache主配置文件方案

1. 启用mod_rewrite(若未启用)

执行以下命令启用模块并重启Apache:

a2enmod rewrite
systemctl restart apache2

2. 配置虚拟主机

针对三个域名分别编写虚拟主机规则,将对应路径的请求转发到实际的/var/www/html/index.php:

(1)newestappname.mydomain 配置

<VirtualHost *:80>
    ServerName newestappname.mydomain
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        AllowOverride None  # 关闭.htaccess,提升安全与性能
        Require all granted
        DirectoryIndex index.php  # 默认指向index.php
    </Directory>
</VirtualHost>

(2)oldappname.mydomain 配置

<VirtualHost *:80>
    ServerName oldappname.mydomain
    DocumentRoot /var/www/html  # 根目录可任意设置,核心靠重写规则转发

    RewriteEngine On
    # 将/appnew/v1.1/下的所有请求转发到实际应用,保留查询参数(QSA)
    RewriteRule ^/appnew/v1.1/(.*)$ /var/www/html/index.php [L,QSA]

    <Directory /var/www/html>
        Require all granted
    </Directory>
</VirtualHost>

(3)oldestappname.mydomain 配置

<VirtualHost *:80>
    ServerName oldestappname.mydomain
    DocumentRoot /var/www/html

    RewriteEngine On
    # 将/app/v1/下的所有请求转发到实际应用,保留查询参数
    RewriteRule ^/app/v1/(.*)$ /var/www/html/index.php [L,QSA]

    <Directory /var/www/html>
        Require all granted
    </Directory>
</VirtualHost>

方案优势

  • 彻底消除符号链接依赖,Git仅需管理/var/www/html/index.php和虚拟主机配置文件(可单独归档)。
  • 避免Git对符号链接的兼容性问题(无需处理符号链接的跟踪、跨系统解析等问题)。

二、.htaccess + mod_rewrite方案

1. 启用mod_rewrite与AllowOverride

确保mod_rewrite已启用(同主配置方案的启用命令),并在对应虚拟主机的<Directory>块中设置:

AllowOverride FileInfo  # 允许.htaccess中的重写规则生效

2. 编写.htaccess规则

在/var/www/html目录下创建.htaccess文件,添加以下规则:

RewriteEngine On

# 匹配newestappname.mydomain的根路径请求
RewriteCond %{HTTP_HOST} ^newestappname\.mydomain$
RewriteRule ^index\.php$ /index.php [L,QSA]

# 匹配oldappname.mydomain的/appnew/v1.1/index.php请求
RewriteCond %{HTTP_HOST} ^oldappname\.mydomain$
RewriteRule ^appnew/v1.1/index\.php$ /index.php [L,QSA]

# 匹配oldestappname.mydomain的/app/v1/index.php请求
RewriteCond %{HTTP_HOST} ^oldestappname\.mydomain$
RewriteRule ^app/v1/index\.php$ /index.php [L,QSA]

# 若需支持对应路径下的所有请求(而非仅index.php),可替换为:
# RewriteCond %{HTTP_HOST} ^oldappname\.mydomain$
# RewriteRule ^appnew/v1.1/(.*)$ /index.php [L,QSA]

方案注意事项

  • 若站点有其他.htaccess规则,需确保重写规则的顺序合理,避免冲突。
  • 性能略低于主配置方案,因Apache需在每次请求时读取并解析.htaccess文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 23:14:52