本文最后更新于 2025年10月10日。
我使用# Domain Swapper插件效果不错
在 WordPress 中配置多域名,可以让同一个站点通过多个不同的域名访问。这通常可以通过修改 WordPress 的设置、使用插件或修改服务器配置文件来实现。以下是几种常见的方法:
方法 1:通过 WordPress 设置
-
修改站点地址:
- 登录 WordPress 后台。
- 前往 设置 > 常规。
- 修改 WordPress 地址(URL) 和 站点地址(URL) 为你希望的主域名。
- 点击 保存更改。
-
允许其他域名访问:
-
打开网站根目录下的
wp-config.php文件。 -
在
/* That's all, stop editing! Happy blogging. */这行代码之前,添加以下代码:define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST']); define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST']);
这段代码的作用是让 WordPress 动态地根据当前的域名来设置
WP_SITEURL和WP_HOME。 -
方法 2:使用 Nginx/Apache 配置文件
如果你使用的是 Nginx 或 Apache,可以在服务器的配置文件中进行重定向和设置,以支持多域名。
Nginx 配置示例编辑你的 Nginx 站点配置文件(通常位于 /etc/nginx/sites-available/your-site),添加或修改 server_name 指令:
server {
listen 80;
server_name example.com www.example.com anotherdomain.com www.anotherdomain.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
Apache 配置示例
编辑你的 Apache 站点配置文件(通常位于 /etc/apache2/sites-available/your-site.conf),添加或修改 ServerName 和 ServerAlias 指令:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com anotherdomain.com www.anotherdomain.com
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
方法 3:使用插件
有一些插件可以帮助你更方便地管理多域名,例如:- Multiple Domain: 允许你在 WordPress 后台管理多个域名。
- Polylang: 虽然主要是多语言插件,但它也支持为每种语言配置不同的域名。
方法 4:数据库层面
如果你的站点已经运行了一段时间,并且有很多硬编码的 URL,你可能需要在数据库中批量替换旧域名为新域名。可以使用插件如 Better Search Replace 来安全地进行数据库字符串替换操作。
注意事项
- SSL/TLS 证书:如果你使用了 HTTPS,需要确保所有域名都有有效的 SSL/TLS 证书。可以通过 Let’s Encrypt 获取免费的证书。
- SEO 优化:为了避免搜索引擎认为你的内容是重复内容,建议设置首选域名(Preferred Domain),并在 Google Search Console 中配置。
- Cookies 和会话:多域名情况下需要注意 Cookies 的作用范围,避免用户登录状态丢失等问题。
通过以上方法,你可以轻松地在 WordPress 中配置多域名,满足不同的业务需求。希望这些信息对你有帮助!<sup>[1]</sup><sup>[2]</sup><sup>[3]</sup>
[1] https://wordpress.org/plugins/multiple-domain/
[2] https://wordpress.org/plugins/better-search-replace/
[3] https://www.linode.com/docs/guides/how-to-install-wordpress-on-ubuntu-20-04/