[英]Redirect domain name in Laravel
我想將Laravel 5中的短鏈接域重定向到例如xyz.com到examplesite.com,同時保持URI請求。 例如:
xyz.com/something?foo=var
將重定向到:
example.com/something?foo=var
我試圖在路由中使用域組,但它似乎不適用於域名級別,只有子域。 我選擇的另一個選項是MiddleWare路線。
我已經設置了一個工作中間件“RedirectsMiddleware”並在我的路由文件中有以下內容:
Route::group(['middleware' => ['redirects'] ], function () {
Route::get('/', 'HoldingSiteController@home');
});
我的RedirectsMiddleware看起來像這樣:
...
public function handle($request, Closure $next)
{
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$host = $_SERVER['SERVER_NAME'];
$defaulthost = 'example.com';
if($host != $defaulthost) {
return Redirect::to($protocol . $defaulthost . $_SERVER['REQUEST_URI']);
}
return $next($request);
}
...
當只請求“example.com”或“example.com/?something=something”時,它會重定向。 添加到最后的任何路由,例如“example.com/someroute”總是拋出異常,查詢字符串無效。 盡管我的MiddleWare重定向,它似乎正在尋找那條路線:
NotFoundHttpException in RouteCollection.php line 161:
您需要使用通配符路由。 url末尾的GET變量不會以您嘗試的方式更改路徑。 訪問http://example.com/?var1=A “計數”為命中路由定義為Route :: get('/',function(){}),因為您正在訪問帶有GET變量var1的example.com/ 。 換句話說,為了確定HTTP請求應該選擇哪條路由,通常會忽略GET變量。
通配符匹配使用正則表達式路由方法 - > where()
Route::group(['middleware' => ['redirects'] ], function () {
Route::any('/{anything}', 'HoldingSiteController@home')
->where('anything', '.*');
Route::any('/', 'HoldingSiteController@home');
});
如上所示,對於空請求,您還需要空路由any('/')。 這個例子還包括“any”動詞而不是“get”動詞在請求匹配中更加貪婪。
https://laravel.com/docs/5.2/routing#parameters-regular-expression-constraints
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.