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

如何在VPS的不同文件夹中托管多个对应不同域名的网站

问题解答

1. 仅添加A记录无法满足需求

A记录的作用仅为将domain2.com的域名解析指向你的VPS IP地址,但Web服务本身无法自动区分不同域名对应的站点目录,仅配置A记录的前提下,访问domain2.com会默认打开和domain1.com相同的站点内容。

2. 可以通过.htaccess实现需求(仅适用于Apache服务器)

使用该方案的前提是你已经为Apache开启了站点根目录的.htaccess支持(需在Apache的主配置或者虚拟主机配置中设置AllowOverride All),操作步骤如下:

  • 首先将domain2.com添加A记录解析到你的VPS IP
  • 新建/var/www/html2目录,将新站点代码上传到该目录
  • 在原来的站点根目录/var/www/html下新建.htaccess文件,添加如下规则:
RewriteEngine On
# 匹配访问域名为domain2.com的请求
RewriteCond %{HTTP_HOST} ^domain2.com$ [NC]
# 将所有请求转发到html2目录下对应路径
RewriteRule ^(.*)$ /var/www/html2/$1 [L]

注意:如果需要同时支持www.domain2.com,可将匹配规则修改为RewriteCond %{HTTP_HOST} ^(www\.)?domain2.com$ [NC]

更推荐方案:配置Web服务虚拟主机

相比.htaccess配置,直接在Web服务中添加虚拟主机规则性能更高、逻辑更清晰,适配Apache和Nginx两种主流服务:

Apache配置方法

  • 新增虚拟主机配置文件,通常路径为/etc/apache2/sites-available/domain2.conf,写入如下内容:
<VirtualHost *:80>
    ServerName domain2.com
    ServerAlias www.domain2.com
    DocumentRoot /var/www/html2
    <Directory /var/www/html2>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/domain2_error.log
    CustomLog ${APACHE_LOG_DIR}/domain2_access.log combined
</VirtualHost>
  • 执行命令启用配置并重启Apache:
a2ensite domain2.conf
systemctl restart apache2

Nginx配置方法

  • 新增server配置文件,通常路径为/etc/nginx/conf.d/domain2.conf,写入如下内容:
server {
    listen 80;
    server_name domain2.com www.domain2.com;
    root /var/www/html2;
    index index.html index.htm index.php;
    location / {
        try_files $uri $uri/ =404;
    }
}
  • 执行命令验证配置并重启Nginx:
nginx -t
systemctl restart nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:24:02