Skip to content

Commit

Permalink
add redirect for non-codes and root path
Browse files Browse the repository at this point in the history
  • Loading branch information
kringkaste committed Aug 18, 2020
1 parent ea63db0 commit ee39054
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Shortener.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use craft\web\UrlManager;
use codemonauts\shortener\jobs\UpdateShortUrl;
use yii\base\Event;
use yii\web\NotFoundHttpException;


/**
Expand Down Expand Up @@ -54,6 +55,13 @@ public function init()
// Get settings
$settings = $this->getSettings();

// Check for root path in domain
$domain = Craft::parseEnv($settings->domain);
$request = Craft::$app->getRequest();
if ($request->isSiteRequest && stripos($request->hostInfo, $domain) !== false && $request->getUrl() === '/') {
throw new NotFoundHttpException();
}

// Register components
$this->components = [
'shortUrl' => ShortUrl::class,
Expand Down Expand Up @@ -84,6 +92,7 @@ public function init()
Event::on(UrlManager::class, UrlManager::EVENT_REGISTER_SITE_URL_RULES, function(RegisterUrlRulesEvent $event) use ($settings) {
if ($settings->domain !== '') {
$event->rules['//' . Craft::parseEnv($settings->domain) . '/<code:\w+>'] = 'shortener/redirect';
$event->rules['//' . Craft::parseEnv($settings->domain) . '<path:.*>'] = 'shortener/redirect/catch-all';
}
});

Expand Down Expand Up @@ -154,7 +163,7 @@ protected function createSettingsModel()
protected function settingsHtml()
{
return Craft::$app->getView()->renderTemplate('shortener/settings', [
'settings' => $this->getSettings()
'settings' => $this->getSettings(),
]
);
}
Expand Down
5 changes: 5 additions & 0 deletions src/controllers/RedirectController.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,9 @@ public function actionRedirect(string $code)

return $this->redirect($shortUrl->destination, $shortUrl->redirectCode);
}

public function actionCatchAll(string $path)
{
throw new NotFoundHttpException();
}
}

0 comments on commit ee39054

Please sign in to comment.