大网数据广告活动
网站运营与故障问答

Need help setting canonical within PHP

· 52CE 我爱测

First, I want to preface that I am not very good with php so I am looking for some guidance. I'm working on a website using Dreamweaver that is being accessed through .davaccess each php page has the following variables: <?php re…

问题原文

原帖链接 · Rob T · CC BY-SA 4.0

First, I want to preface that I am not very good with php so I am looking for some guidance. I'm working on a website using Dreamweaver that is being accessed through .davaccess

each php page has the following variables:

<?php
require_once "../config.php";
$title="Custom Title I enter";
$metaDescription="Custom Description I enter.";        
include_once (INCLUDES_PATH  . "/header.php");
?>  

And the header.php includes this section:

<title><?php echo $title; ?></title>
<meta name="description" content="<?php echo $metaDescription ?>" />
<base href="<?php echo $config['urls']['baseUrl'] ?>">

My thought is that I need to add something in the header file so I can add my own URL on the individual pages. Based on how the title and description have worked, I tried including the following:

<link rel="canonical" href="<?php echo $canonical ?>" />

but that ends up just making each page canonicalize to the base URL, before I add anything to individual pages.

What I'm looking for is a way to add some code that can autopopulate the current URL as the canonical, and possibly update it on individual pages if necessary. Any help would be greatly appreciated. Thank you

已采纳解答

原帖链接 · Michael Moriarty · CC BY-SA 4.0

What I do for pages that I want to mark as canonical is put the following code in my header.php file that is loaded on each page:
<link rel='canonical' href='<?php echo 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>'>

This loads the prefix https:// plus the domain www.example.com plus the page page.php resulting in
<link rel='canonical' href='https://www.example.com/page.php'>

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2019-10-30)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。