一、问题背景
- WordPress网站备案期间用IP访问,备案后启用域名
- 需要同时保留IP访问(临时使用)和域名访问(正式使用)
- 解决www域名跳转和HTTPS统一问题
二、核心解决方案架构
- Nginx层面:处理域名跳转和SSL
- WordPress层面:动态设置基准URL
- 数据库层面:统一存储主域名路径
三、详细配置步骤
步骤1:Nginx配置(处理跳转)
server_name yuthk.com www.yuthk.com 123.x.x.x;
步骤2:WordPress动态URL配置(wp-config.php)
/* Add any custom values between this line and the "stop editing" line. */
// 动态定义站点URL - 支持IP、www、主域名多方式访问
if (isset($_SERVER['HTTP_HOST'])) {
// 情况1:IP直接访问 - 使用HTTP
if ($_SERVER['HTTP_HOST'] == '123.x.x.') {
define('WP_HOME', 'https://yuthk.com');
define('WP_SITEURL', 'https://yuthk.com');
}
// 情况2:www域名访问 - 统一使用主域名HTTPS
elseif ($_SERVER['HTTP_HOST'] == 'www.yuthk.com') {
define('WP_HOME', 'https://yuthk.com');
define('WP_SITEURL', 'https://yuthk.com');
}
// 情况3:主域名访问 - 使用HTTPS
else {
define('WP_HOME', 'https://yuthk.com');
define('WP_SITEURL', 'https://yuthk.com');
}
}
/* That's all, stop editing! Happy publishing. */
步骤3:数据库统一处理
-- 统一使用主域名存储
UPDATE wp_options SET option_value = 'https://yuthk.com' WHERE option_name = 'siteurl';
UPDATE wp_options SET option_value = 'https://yuthk.com' WHERE option_name = 'home';
-- 替换内容中的IP为主域名
UPDATE wp_posts SET post_content = replace(post_content, 'https://yuthk.com', 'https://yuthk.com');
四、配置原理详解
| 访问方式 | 用户输入 | Nginx处理 | WordPress基准URL | 最终效果 |
|---|---|---|---|---|
| IP直连 | http://IP | 直接访问 | http://IP | IP访问,资源用HTTP |
| www域名 | http://www | 301跳转主域名 | https://主域名 | 跳转后HTTPS访问 |
| 主域名 | http://主域名 | 301跳转HTTPS | https://主域名 | HTTPS安全访问 |
| 主域名 | https://主域名 | 直接访问 | https://主域名 | HTTPS安全访问 |
五、关键技术点解析
- HTTP_HOST变量:PHP获取当前访问域名/IP
- define常量:覆盖WordPress默认的站点URL设置
- Nginx跳转:处理www和HTTP到HTTPS的跳转
- 数据库统一:保证内容存储的一致性
六、其他方案
新建一个www.yyuthk.com站点,重定向到yuthk.com