配置特定于区域性的 URL
具有文化特定的 URL 在 SEO 方面可能是有益的。
例如以下页面的英文版:
http://www.mydomain.com/insurance
将翻译成:
http://www.mydomain.nl/verzekering
代替:
http://www.mydomain.nl/nl-nl/insurance
有更多方法可以实现这一目标:
-
通常,你希望 URL 来自文档的名称。为此,请确保将 URL 路径的使用名称路径 设置为 true。默认情况下,它是错误的。
-
如果默认 URL 创建模式不适合你,你可以按照官方文档中的说明手动设置 URL。但是,只有在需要调整少量 URL 时,此选项才可行。
-
如果要基于自定义模式自动创建 URL,可以实现自定义模块 。
using System;
using System.Text;
using CMS;
using CMS.DataEngine;
using CMS.DocumentEngine;
using CMS.Helpers;
[assembly: RegisterModule(typeof(CultureSpecificUrlsModule))]
public class CultureSpecificUrlsModule : Module
{
public CultureSpecificUrlsModule() : base("CultureSpecificUrlsModule")
{
}
protected override void OnInit()
{
base.OnInit();
/***
* Before the node gets saved, we'll update it's DocumentUrlPath.
* The system will ensure it'll be saved in a valid URL format.
*/
DocumentEvents.Update.Before += Update_Before;
}
private void Update_Before(object sender, DocumentEventArgs e)
{
/***
* Here you can apply conditions before you actually update the DocumentUrlPath.
* E.g. you can check for the document's culture.
*/
UpdateUrlPath(e.Node);
}
public static void UpdateUrlPath(TreeNode node)
{
/***
* You can set the DocumentUrlPath to whatever you want.
* In this example we're using a method extracted from CMS.DocumentEngine.TreePathUtils.
* The same method is used to generate a URL for the default culture.
*/
node.DocumentUrlPath = GetUrlPathFromNamePathInternal(node.DocumentNamePath);
}
internal static string GetUrlPathFromNamePathInternal(string namePath, int level = -1)
{
// Check valid path
if (String.IsNullOrEmpty(namePath) || (namePath == "/"))
{
return null;
}
// For top level the path is always /
if (level == 0)
{
return "/";
}
// Ensure maximal level if not set
if (level < 0)
{
level = Int32.MaxValue;
}
// Get the path parts
string[] pathParts = namePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
int currentLevel = 1;
var path = new StringBuilder();
foreach (string part in pathParts)
{
string shortPart = part;
// Shorten the part to the allowed maximum
if (shortPart.Length > TreePathUtils.MaxAliasLength)
{
shortPart = shortPart.Substring(0, TreePathUtils.MaxAliasLength);
}
path.Append("/", shortPart);
if (++currentLevel > level)
{
break;
}
}
return path.ToString();
}
}
- 如果你需要更新现有页面(例如,如果你在开始开发项目之前忘记检查 URL 路径的使用名称路径 ),你可以使用一个简单的控制台应用程序来为你更新 URL:
using System;
using CMS.DataEngine;
using CMS.DocumentEngine;
namespace CultureUrlsUtil
{
class Program
{
static void Main(string[] args)
{
CMSApplication.Init();
/*** Here you can narrow down the scope of documents that should be updated using DocumentQuery ***/
var pages = DocumentHelper.GetDocuments().Culture("es-es");
foreach (var page in pages)
{
/*** Here we are calling code from the example above. ***/
CultureSpecificUrlsModule.UpdateUrlPath(page);
page.Update();
}
Console.Write("URLs created!");
Console.ReadLine();
}
}
}