Laravel中如何在WordPress的/forum路由前执行自定义中间件?
这个问题的核心原因是Web服务器会优先匹配物理存在的目录——当你访问/forum时,服务器直接指向了public/forum下的WordPress文件,完全跳过了Laravel的路由和中间件流程。要让中间件生效,我们需要先让请求经过Laravel,再转发到WordPress。
下面是分步解决方案:
1. 修改Web服务器配置,让/forum请求先经过Laravel
首先要调整服务器规则,强制/forum的所有请求都先进入Laravel的index.php,而不是直接访问物理目录。
Apache(修改public/.htaccess)
找到Laravel根目录下public/.htaccess文件,在"Send Requests To Front Controller..."部分之前,添加一条规则:
# 让/forum请求优先经过Laravel RewriteRule ^forum(/.*)?$ index.php [L]
完整的.htaccess大概是这样:
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # 让/forum请求优先经过Laravel RewriteRule ^forum(/.*)?$ index.php [L] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>
Nginx(修改站点配置)
在你的Nginx站点配置中,为/forum添加单独的规则,确保请求转发到Laravel入口:
server { listen 80; server_name localhost; root /path/to/laravel/public; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } # 强制/forum请求经过Laravel location ^~ /forum { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 根据你的PHP版本调整 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } }
修改后记得重启Nginx服务。
2. 在Laravel中配置路由和中间件
现在请求会经过Laravel了,我们可以定义路由并绑定你的wp_login中间件,最后转发请求到WordPress。
在routes/web.php中添加:
Route::get('/forum{any?}', function ($any = '') { // 指向WordPress的入口文件 $wpEntry = public_path('forum/index.php'); // 重置服务器变量,让WordPress正确识别请求路径 $_SERVER['REQUEST_URI'] = "/forum{$any}"; $_SERVER['SCRIPT_NAME'] = "/forum/index.php"; $_SERVER['SCRIPT_FILENAME'] = $wpEntry; // 加载WordPress require $wpEntry; exit; // 确保执行完WordPress后直接退出,不返回Laravel流程 })->middleware('wp_login')->where('any', '.*');
{any?}通配符可以匹配/forum下的所有子路径(比如/forum/wp-admin)where('any', '.*')确保通配符能匹配包含斜杠的路径
3. 调整WordPress配置(可选但建议)
为了避免WordPress生成错误的链接,打开public/forum/wp-config.php,添加以下配置:
define('WP_HOME', 'http://localhost:8000/forum'); define('WP_SITEURL', 'http://localhost:8000/forum');
验证效果
现在访问http://localhost:8000/forum,查看Laravel的日志文件(storage/logs/laravel.log),你应该能看到中间件里的test forum lalalala日志,同时WordPress页面能正常加载——这就说明中间件已经在WordPress请求前执行了。
内容的提问来源于stack exchange,提问作者Luís Henriques

