feat: 外链中转 /go——点击统计 + 拦截 + 隐藏真实链接
- redirects 表 + UrlRedirector:go_url() 站外链接改写为 /go/{hash}(确定性 hash、同 URL 复用、并发安全、缓存)
- /go/{hash} 302 跳转 + 点击计数 + 最后点击时间;停用状态 410(二次拦截);后台「外链中转」资源可查看点击量/启停/删除
- 接入点:正文外链(渲染器统一改写)、评论正文自动链接(comment_body)、评论作者网址、友链(侧边栏+友链页);站内/相对/mailto/tel/锚点不中转
- 测试 6 个(改写/计数/拦截/复用/渲染/评论正文);README 补充
This commit is contained in:
@@ -104,6 +104,12 @@ php artisan workerman:serve stop
|
||||
- 失败重试:`WORKERMAN_MAX_TRIES`(默认 3),超时 `WORKERMAN_TIMEOUT`(默认 60s),重试耗尽进 `failed_jobs` 表
|
||||
- 降级路径:`php artisan queue:work` 照常可用(同一队列)
|
||||
|
||||
## 外链中转(/go)
|
||||
|
||||
- 正文外链、评论正文 URL、评论作者网址、友链统一改写为 `/go/{hash}`:302 跳转 + **点击统计**、可**停用拦截**(返回 410)、隐藏真实链接、为未来广告位预留
|
||||
- 站内链接/相对路径/mailto/tel/锚点不中转;同一 URL 复用同一短码
|
||||
- 后台「外链中转」可查看点击量、按状态筛选、启停
|
||||
|
||||
## 前台缓存
|
||||
|
||||
- 匿名 GET 页面整页缓存(首页/列表/文章/归档/标签等),TTL 默认 300 秒(`PAGE_CACHE_TTL`),命中时零数据库查询
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Blog\Controllers;
|
||||
|
||||
use App\Models\Redirect;
|
||||
|
||||
class GoController
|
||||
{
|
||||
/**
|
||||
* 外链中转跳转:计数 + 302。停用的链接返回 410(可作二次拦截)。
|
||||
*/
|
||||
public function show(string $hash)
|
||||
{
|
||||
$redirect = Redirect::query()->where('hash', $hash)->firstOrFail();
|
||||
|
||||
if (! $redirect->isActive()) {
|
||||
abort(410);
|
||||
}
|
||||
|
||||
$redirect->hit();
|
||||
|
||||
return redirect()->away($redirect->target_url, 302);
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,31 @@ class PostContentRenderer
|
||||
$html = app(\App\Blog\Support\PluginManager::class)->applyFilters('post.rendered', $html, $post);
|
||||
|
||||
// 兜底:任何情况下不把裸 [paid] 标签输出到页面(如会员插件被停用时)
|
||||
return preg_replace('/\[(\/?paid)\]/i', '', $html);
|
||||
$html = preg_replace('/\[(\/?paid)\]/i', '', $html);
|
||||
|
||||
// 外链中转:站外链接改写为 /go/{hash}(点击统计/拦截)
|
||||
return $this->rewriteExternalLinks($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把正文里的站外 <a href> 改写为 /go 中转地址(站内/相对/锚点/mailto 不变)。
|
||||
*/
|
||||
private function rewriteExternalLinks(string $html): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/<a\s+([^>]*?href=["\'])([^"\']+)(["\'][^>]*)>(.*?)<\/a>/is',
|
||||
function (array $m): string {
|
||||
$url = html_entity_decode(trim($m[2]));
|
||||
$go = go_url($url);
|
||||
|
||||
if ($go === $url) {
|
||||
return $m[0];
|
||||
}
|
||||
|
||||
return '<a '.$m[1].e($go).$m[3].'>'.$m[4].'</a>';
|
||||
},
|
||||
$html
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Blog\Services;
|
||||
|
||||
use App\Models\Redirect;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* 外链中转:把站外链接改写为 /go/{hash},用于点击统计、二次拦截与未来广告位。
|
||||
* 站内链接、相对路径、mailto/tel/锚点不中转。
|
||||
*/
|
||||
class UrlRedirector
|
||||
{
|
||||
public function goUrl(string $url): string
|
||||
{
|
||||
$url = trim((string) $url);
|
||||
|
||||
if (! $this->isExternal($url)) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
return route('go.show', $this->hashFor($url));
|
||||
}
|
||||
|
||||
public function isExternal(string $url): bool
|
||||
{
|
||||
if (! preg_match('#^https?://#i', $url)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$host = parse_url($url, PHP_URL_HOST);
|
||||
|
||||
if (! $host) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$internalHost = parse_url((string) config('app.url'), PHP_URL_HOST);
|
||||
|
||||
return strcasecmp($host, (string) $internalHost) !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取 URL 对应的短 hash(确定性:同一 URL 复用同一条记录,并发安全)。
|
||||
*/
|
||||
public function hashFor(string $url): string
|
||||
{
|
||||
return Cache::remember('go.hash.'.md5($url), now()->addDay(), function () use ($url) {
|
||||
$hash = substr(hash('sha256', $url), 0, 10);
|
||||
|
||||
for ($i = 0; $i < 3; $i++) {
|
||||
try {
|
||||
Redirect::create(['hash' => $hash, 'target_url' => $url]);
|
||||
|
||||
return $hash;
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
$existing = Redirect::where('target_url', $url)->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing->hash;
|
||||
}
|
||||
|
||||
$hash = substr(hash('sha256', $url.$i), 0, 10);
|
||||
}
|
||||
}
|
||||
|
||||
return $hash;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Resources\RedirectResource\Pages\ListRedirects;
|
||||
use App\Models\Redirect;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class RedirectResource extends Resource
|
||||
{
|
||||
protected static \UnitEnum|string|null $navigationGroup = '管理';
|
||||
|
||||
protected static ?string $model = Redirect::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowUturnRight;
|
||||
|
||||
protected static ?string $navigationLabel = '外链中转';
|
||||
|
||||
protected static ?string $pluralModelLabel = '外链中转';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('hash')
|
||||
->label('短码')
|
||||
->badge()
|
||||
->color('gray'),
|
||||
TextColumn::make('target_url')
|
||||
->label('目标地址')
|
||||
->limit(50)
|
||||
->copyable()
|
||||
->searchable(),
|
||||
TextColumn::make('clicks')
|
||||
->label('点击量')
|
||||
->numeric()
|
||||
->sortable(),
|
||||
TextColumn::make('status')
|
||||
->label('状态')
|
||||
->badge()
|
||||
->formatStateUsing(fn ($state) => $state === 'active' ? '启用' : '停用')
|
||||
->color(fn ($state) => $state === 'active' ? 'success' : 'danger'),
|
||||
TextColumn::make('last_clicked_at')
|
||||
->label('最后点击')
|
||||
->dateTime('Y-m-d H:i')
|
||||
->placeholder('—')
|
||||
->sortable(),
|
||||
TextColumn::make('created_at')
|
||||
->label('创建时间')
|
||||
->dateTime('Y-m-d H:i')
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->filters([
|
||||
\Filament\Tables\Filters\SelectFilter::make('status')
|
||||
->label('状态')
|
||||
->options(['active' => '启用', 'disabled' => '停用']),
|
||||
], \Filament\Tables\Enums\FiltersLayout::AboveContent)
|
||||
->recordActions([
|
||||
Action::make('toggle')
|
||||
->label(fn (Redirect $record) => $record->isActive() ? '停用' : '启用')
|
||||
->color(fn (Redirect $record) => $record->isActive() ? 'danger' : 'success')
|
||||
->action(fn (Redirect $record) => $record->update(['status' => $record->isActive() ? 'disabled' : 'active'])),
|
||||
DeleteAction::make(),
|
||||
])
|
||||
->recordUrl(null)
|
||||
->recordAction(null)
|
||||
->defaultSort('clicks', 'desc');
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListRedirects::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\RedirectResource\Pages;
|
||||
|
||||
use App\Filament\Resources\RedirectResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListRedirects extends ListRecords
|
||||
{
|
||||
protected static string $resource = RedirectResource::class;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Redirect extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'hash', 'target_url', 'clicks', 'status', 'last_clicked_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'last_clicked_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->status === 'active';
|
||||
}
|
||||
|
||||
public function hit(): void
|
||||
{
|
||||
$this->increment('clicks');
|
||||
$this->update(['last_clicked_at' => now()]);
|
||||
}
|
||||
}
|
||||
@@ -42,3 +42,31 @@ if (! function_exists('blog_setting')) {
|
||||
return \App\Models\Setting::get($key, $default);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('go_url')) {
|
||||
/**
|
||||
* 外链中转:站外链接改写为 /go/{hash}(点击统计/拦截),站内链接原样返回。
|
||||
*/
|
||||
function go_url(string $url): string
|
||||
{
|
||||
return app(\App\Blog\Services\UrlRedirector::class)->goUrl($url);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('comment_body')) {
|
||||
/**
|
||||
* 评论正文:转义 + 自动链接 URL(走 /go 中转,nofollow)。
|
||||
*/
|
||||
function comment_body(string $text): string
|
||||
{
|
||||
$text = e($text);
|
||||
|
||||
$text = preg_replace_callback(
|
||||
'#(https?://[^\s<>"\'()]+)#i',
|
||||
fn (array $m) => '<a href="'.e(go_url($m[1])).'" target="_blank" rel="nofollow noopener">'.$m[1].'</a>',
|
||||
$text
|
||||
);
|
||||
|
||||
return nl2br($text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('redirects', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('hash', 16)->unique();
|
||||
$table->text('target_url');
|
||||
$table->unsignedBigInteger('clicks')->default(0);
|
||||
$table->string('status', 20)->default('active'); // active / disabled
|
||||
$table->timestamp('last_clicked_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index('target_url');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('redirects');
|
||||
}
|
||||
};
|
||||
@@ -8,7 +8,7 @@
|
||||
<ul class="links-list">
|
||||
@forelse($links as $link)
|
||||
<li>
|
||||
<a href="{{ $link->url }}" target="_blank" rel="noopener nofollow">{{ $link->name }}</a>
|
||||
<a href="{{ go_url($link->url) }}" target="_blank" rel="noopener nofollow">{{ $link->name }}</a>
|
||||
@if($link->note)<span class="link-note">— {{ $link->note }}</span>@endif
|
||||
</li>
|
||||
@empty
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
<h3 class="widget-title">友情链接</h3>
|
||||
<ul class="widget-list">
|
||||
@forelse($links as $link)
|
||||
<li><a href="{{ $link->url }}" target="_blank" rel="noopener">{{ $link->name }}</a></li>
|
||||
<li><a href="{{ go_url($link->url) }}" target="_blank" rel="noopener">{{ $link->name }}</a></li>
|
||||
@empty
|
||||
<li>暂无链接</li>
|
||||
@endforelse
|
||||
|
||||
@@ -68,11 +68,11 @@
|
||||
<div class="comment-head">
|
||||
<strong>{{ $comment->author_name }}</strong>
|
||||
@if($comment->author_url)
|
||||
<span>· <a href="{{ $comment->author_url }}" target="_blank" rel="noopener nofollow">访问主页</a></span>
|
||||
<span>· <a href="{{ go_url($comment->author_url) }}" target="_blank" rel="noopener nofollow">访问主页</a></span>
|
||||
@endif
|
||||
<span class="comment-time">· {{ $comment->created_at->format(blog_setting('comment_timeformat', 'Y-m-d H:i')) }}</span>
|
||||
</div>
|
||||
<div class="comment-body">{!! nl2br(e($comment->content)) !!}</div>
|
||||
<div class="comment-body">{!! comment_body($comment->content) !!}</div>
|
||||
</div>
|
||||
@empty
|
||||
<p class="empty">暂无评论</p>
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Blog\Controllers\AuthController;
|
||||
use App\Blog\Controllers\CategoryController;
|
||||
use App\Blog\Controllers\CommentController;
|
||||
use App\Blog\Controllers\FeedController;
|
||||
use App\Blog\Controllers\GoController;
|
||||
use App\Blog\Controllers\HomeController;
|
||||
use App\Blog\Controllers\LegacyController;
|
||||
use App\Blog\Controllers\LinkController;
|
||||
@@ -38,6 +39,9 @@ Route::post('/posts/{post}/comments', [CommentController::class, 'store'])->name
|
||||
// 浏览量统计(独立端点,避开整页缓存,保证实时)
|
||||
Route::get('/track-view/{post}', fn (\App\Models\Post $post) => response($post->increment('views') ? '' : '', 204))->name('track-view');
|
||||
|
||||
// 外链中转:/go/{hash} 302 跳转,记录点击量;停用状态返回 410
|
||||
Route::get('/go/{hash}', [GoController::class, 'show'])->name('go.show');
|
||||
|
||||
Route::get('/category/{slug}.shtml', [CategoryController::class, 'show'])->where('slug', '[^/]+')->name('category.show');
|
||||
Route::get('/category/{slug}', fn (string $slug) => redirect()->route('category.show', $slug, 301))->where('slug', '[^/]+');
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ class AdminPagesTest extends TestCase
|
||||
$this->actingAs($this->admin)->get('/admin/plugins')->assertOk();
|
||||
$this->actingAs($this->admin)->get('/admin/payments')->assertOk();
|
||||
$this->actingAs($this->admin)->get('/admin/ai-settings')->assertOk();
|
||||
$this->actingAs($this->admin)->get('/admin/redirects')->assertOk();
|
||||
}
|
||||
|
||||
public function test_guest_is_redirected_to_login(): void
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Blog\Services\PostContentRenderer;
|
||||
use App\Blog\Services\UrlRedirector;
|
||||
use App\Models\Post;
|
||||
use App\Models\Redirect;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class GoRedirectTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_go_url_rewrites_external_but_keeps_internal(): void
|
||||
{
|
||||
$go = app(UrlRedirector::class);
|
||||
|
||||
$this->assertStringContainsString('/go/', $go->goUrl('https://example.com/path'));
|
||||
$this->assertSame('http://laralog.test/posts/1', $go->goUrl('http://laralog.test/posts/1'));
|
||||
$this->assertSame('/posts/1', $go->goUrl('/posts/1'));
|
||||
$this->assertSame('mailto:a@b.com', $go->goUrl('mailto:a@b.com'));
|
||||
$this->assertSame('#anchor', $go->goUrl('#anchor'));
|
||||
}
|
||||
|
||||
public function test_go_redirect_counts_clicks(): void
|
||||
{
|
||||
$redirect = Redirect::create([
|
||||
'hash' => 'abc123def0',
|
||||
'target_url' => 'https://example.com/target',
|
||||
]);
|
||||
|
||||
$this->get('/go/abc123def0')
|
||||
->assertRedirect('https://example.com/target');
|
||||
|
||||
$redirect->refresh();
|
||||
$this->assertSame(1, $redirect->clicks);
|
||||
$this->assertNotNull($redirect->last_clicked_at);
|
||||
}
|
||||
|
||||
public function test_disabled_redirect_returns_410(): void
|
||||
{
|
||||
Redirect::create([
|
||||
'hash' => 'blocked0000',
|
||||
'target_url' => 'https://example.com/bad',
|
||||
'status' => 'disabled',
|
||||
]);
|
||||
|
||||
$this->get('/go/blocked0000')->assertStatus(410);
|
||||
}
|
||||
|
||||
public function test_same_url_reuses_same_hash(): void
|
||||
{
|
||||
$a = app(UrlRedirector::class)->goUrl('https://example.com/dup');
|
||||
$b = app(UrlRedirector::class)->goUrl('https://example.com/dup');
|
||||
|
||||
$this->assertSame($a, $b);
|
||||
$this->assertSame(1, Redirect::query()->where('target_url', 'https://example.com/dup')->count());
|
||||
}
|
||||
|
||||
public function test_post_render_rewrites_external_links(): void
|
||||
{
|
||||
$post = Post::create([
|
||||
'title' => '外链测试',
|
||||
'slug' => 'go-test',
|
||||
'content' => "正文 <a href=\"https://example.com/x\" target=\"_blank\">外链</a> 和 <a href=\"http://laralog.test/posts/1\">站内</a>",
|
||||
'content_format' => 'html',
|
||||
'status' => 'published',
|
||||
'published_at' => now(),
|
||||
]);
|
||||
|
||||
$html = app(PostContentRenderer::class)->render($post);
|
||||
|
||||
$this->assertStringContainsString('href="http://laralog.test/go/', $html);
|
||||
$this->assertStringContainsString('href="http://laralog.test/posts/1"', $html);
|
||||
$this->assertStringNotContainsString('href="https://example.com/x"', $html);
|
||||
}
|
||||
|
||||
public function test_comment_body_autolinks_and_redirects(): void
|
||||
{
|
||||
$html = comment_body('看看 https://example.com/note 这个链接');
|
||||
|
||||
$this->assertStringContainsString('href="http://laralog.test/go/', $html);
|
||||
$this->assertStringContainsString('rel="nofollow noopener"', $html);
|
||||
$this->assertStringNotContainsString('href="https://example.com/note"', $html);
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@
|
||||
<h3>友情链接</h3>
|
||||
<ul>
|
||||
@forelse($links as $link)
|
||||
<li><a href="{{ $link->url }}" target="_blank" rel="noopener">{{ $link->name }}</a></li>
|
||||
<li><a href="{{ go_url($link->url) }}" target="_blank" rel="noopener">{{ $link->name }}</a></li>
|
||||
@empty
|
||||
<li>暂无链接</li>
|
||||
@endforelse
|
||||
|
||||
@@ -66,10 +66,10 @@
|
||||
<div class="comment" id="comment-{{ $comment->id }}">
|
||||
<div class="comment-head">
|
||||
<strong>{{ $comment->author_name }}</strong>
|
||||
@if($comment->author_url)<span>· <a href="{{ $comment->author_url }}" target="_blank" rel="noopener nofollow">访问主页</a></span>@endif
|
||||
@if($comment->author_url)<span>· <a href="{{ go_url($comment->author_url) }}" target="_blank" rel="noopener nofollow">访问主页</a></span>@endif
|
||||
<span class="comment-time">· {{ $comment->created_at->format(blog_setting('comment_timeformat', 'Y-m-d H:i')) }}</span>
|
||||
</div>
|
||||
<div class="comment-body">{!! nl2br(e($comment->content)) !!}</div>
|
||||
<div class="comment-body">{!! comment_body($comment->content) !!}</div>
|
||||
</div>
|
||||
@empty
|
||||
<p class="empty">暂无评论</p>
|
||||
|
||||
Reference in New Issue
Block a user