Nginx反向代理+Apache2部署WordPress重定向至localhost问题求助
WordPress子目录重定向至localhost问题排查与解决
问题描述
在example.com/wordpress/子目录安装WordPress后,访问http://example.com/wordpress/会被重定向到https://localhost/wordpress/。已修改数据库wp_options表的siteurl和home字段为http://example.com/wordpress/,但问题仍未解决。
当前环境配置
Nginx反向代理配置(监听80、443端口)
server { server_name example.com; location / { proxy_pass http://localhost:8080; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name example.com; listen 80; return 404; # managed by Certbot }
Apache2配置(监听8080端口)
<VirtualHost *:8080> DocumentRoot "/var/www/example.com" ServerName example.com <Directory "/var/www/example.com"> Options MultiViews FollowSymlinks AllowOverride All Order allow,deny Allow from all </Directory> TransferLog /var/log/apache2/nextcloud_access.log ErrorLog /var/log/apache2/nextcloud_error.log </VirtualHost>
解决步骤
1. 补全Nginx代理请求头部
Apache后端无法获取真实的客户端请求域名和协议,导致WordPress生成错误重定向地址。在Nginx的location /块中添加以下代理头部:
location / { proxy_pass http://localhost:8080; # 新增以下配置 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }
Host $host:让Apache识别真实请求域名example.com,而非localhost:8080X-Forwarded-Proto $scheme:告知WordPress当前请求使用的是HTTP/HTTPS协议
2. 配置Apache信任代理请求
确保Apache启用mod_remoteip模块(执行a2enmod remoteip后重启Apache),并在VirtualHost中添加以下配置:
<VirtualHost *:8080> # 原有配置... RemoteIPHeader X-Forwarded-For RemoteIPInternalProxy 127.0.0.1 UseCanonicalName Off </VirtualHost>
UseCanonicalName Off:禁用Apache自动生成规范域名重定向,强制使用请求中的Host头部
3. 强制WordPress使用正确地址
在WordPress的wp-config.php文件中添加以下代码,直接指定站点地址:
define('WP_HOME', 'https://example.com/wordpress/'); define('WP_SITEURL', 'https://example.com/wordpress/'); define('FORCE_SSL_ADMIN', true); // 适配反向代理下的SSL检测 if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') { $_SERVER['HTTPS'] = 'on'; }
4. 清理缓存
修改配置后,清空浏览器缓存(快捷键Ctrl+Shift+Delete),若使用WordPress缓存插件,需同时清空插件缓存,避免旧规则残留。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

