如何在Laravel Blade中仅为Beta域名添加noindex元标签
解决方案:Laravel Blade 按域名控制 noindex 元标签
你的疑问解答
直接添加固定的noindex标签会让两个域名都生效,无法自动区分正式和Beta域名,必须通过代码判断当前访问的域名,再决定是否输出该标签。
具体实现方法
方法一:直接在Blade模板中判断域名
把你当前固定的<meta name="robots" content="noindex">替换成以下条件判断代码:
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}"> <!-- 按域名判断是否添加noindex --> @if(request()->getHost() === 'www.beta.example.com') <meta name="robots" content="noindex"> @endif <script type='application/ld+json'> { "@context": "http:\/\/schema.org", "@type": "WebSite", "@id": "#website", "url": "{{ route('home') }}", "name": "{{ config('app.name', 'Know Before You Go') }}", "alternateName": "Know Before You Go" } </script> @if(isset($seo)) {{ $seo }} @else <title>{{ __("seo.homepage.title") }}</title> @endif <link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' /> <!-- Fonts --> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=PT+Serif&display=swap" rel="stylesheet"> <!-- Styles --> @vite('resources/css/app.css') @livewireStyles </head>
当用户访问www.beta.example.com时,会自动输出noindex标签;访问正式域名时则不会。
方法二:通过环境变量配置(更灵活)
如果后续可能修改域名,推荐把域名配置到.env文件中:
# .env文件中添加 APP_PROD_DOMAIN=www.example.com APP_BETA_DOMAIN=www.beta.example.com
然后在Blade模板中使用环境变量判断:
@if(request()->getHost() === env('APP_BETA_DOMAIN')) <meta name="robots" content="noindex"> @endif
这种方式无需修改模板代码,只需调整.env即可切换域名规则。
注意事项
确保你的服务器已正确配置,让两个域名都指向同一个Laravel项目根目录,这样request()->getHost()才能准确获取当前访问的域名。
内容的提问来源于stack exchange,提问作者Waleed Tariq
相关产品推荐
相关产品推荐

