HUGO

  • 新闻
  • 文档
  • 主题
  • 作品展示
  • 社区
  • GitHub
    • English
    • 中文

What's on this Page

  • 配置文件
  • 配置目录
  • 所有的配置设置
  • 配置构建
  • 配置标题案例
  • 配置环境变量
  • 配置查找顺序
  • 示例配置
  • 配置与环境变量
  • 忽略内容文件当渲染
  • 配置前页
    • 配置日期
  • 配置额外的输出格式
  • 配置文件高速缓存
    • 关键字解释
  • 配置格式规范
GETTING STARTED FUNDAMENTALS

配置 Hugo

如何配置你的Hugo网站。

配置文件

Hugo uses the config.toml, config.yaml, or config.json (if found in the site root) as the default site config file.

The user can choose to override that default with one or more site config files using the command line --config switch.

Examples:

hugo --config debugconfig.toml
hugo --config a.toml,b.toml,c.toml

Multiple site config files can be specified as a comma-separated string to the --config switch.

配置目录

In addition to using a single site config file, one can use the configDir directory (default to config/) to maintain easier organization and environment specific settings.

  • Each file represents a configuration root object, such as Params, Menus, Languages etc…
  • Each directory holds a group of files containing settings unique to an environment.
  • Files can be localized to become language specific.
├── config
│   ├── _default
│   │   ├── config.toml
│   │   ├── languages.toml
│   │   ├── menus.en.toml
│   │   ├── menus.zh.toml
│   │   └── params.toml
│   ├── production
│   │   ├── config.toml
│   │   └── params.toml
│   └── staging
│       ├── config.toml
│       └── params.toml

Considering the structure above, when running hugo --environment staging, Hugo will use every settings from config/_default and merge staging's on top of those.

Default environments are development with hugo serve and production with hugo.

所有的配置设置

The following is the full list of Hugo-defined variables with their default value in parentheses. Users may choose to override those values in their site config file(s).

archetypeDir (“archetypes”)
The directory where Hugo finds archetype files (content templates). Also see Module Mounts Config for an alternative way to configure this directory (from Hugo 0.56).
assetDir (“assets”)
The directory where Hugo finds asset files used in Hugo Pipes. Also see Module Mounts Config for an alternative way to configure this directory (from Hugo 0.56).
baseURL
Hostname (and path) to the root, e.g. https://bep.is/
blackfriday
See Configure Blackfriday
build
See Configure Build
buildDrafts (false)
Include drafts when building.
buildExpired (false)
Include content already expired.
buildFuture (false)
Include content with publishdate in the future.
caches
See Configure File Caches
canonifyURLs (false)
Enable to turn relative URLs into absolute.
contentDir (“content”)
The directory from where Hugo reads content files. Also see Module Mounts Config for an alternative way to configure this directory (from Hugo 0.56).
dataDir (“data”)
The directory from where Hugo reads data files. Also see Module Mounts Config for an alternative way to configure this directory (from Hugo 0.56).
defaultContentLanguage (“en”)
Content without language indicator will default to this language.
defaultContentLanguageInSubdir (false)
Render the default content language in subdir, e.g. content/en/. The site root / will then redirect to /en/.
disableAliases (false)
Will disable generation of alias redirects. Note that even if disableAliases is set, the aliases themselves are preserved on the page. The motivation with this is to be able to generate 301 redirects in an .htaccess, a Netlify _redirects file or similar using a custom output format.
disableHugoGeneratorInject (false)
Hugo will, by default, inject a generator meta tag in the HTML head on the home page only. You can turn it off, but we would really appreciate if you don’t, as this is a good way to watch Hugo’s popularity on the rise.
disableKinds ([])
Enable disabling of all pages of the specified Kinds. Allowed values in this list: "page", "home", "section", "taxonomy", "taxonomyTerm", "RSS", "sitemap", "robotsTXT", "404".
disableLiveReload (false)
Disable automatic live reloading of browser window.
disablePathToLower (false)
Do not convert the url/path to lowercase.
enableEmoji (false)
Enable Emoji emoticons support for page content; see the Emoji Cheat Sheet.
enableGitInfo (false)
Enable .GitInfo object for each page (if the Hugo site is versioned by Git). This will then update the Lastmod parameter for each page using the last git commit date for that content file.
enableInlineShortcodes
Enable inline shortcode support. See Inline Shortcodes.
enableMissingTranslationPlaceholders (false)
Show a placeholder instead of the default value or an empty string if a translation is missing.
enableRobotsTXT (false)
Enable generation of robots.txt file.
frontmatter

See Front matter Configuration.

footnoteAnchorPrefix ("")
Prefix for footnote anchors.
footnoteReturnLinkContents ("")
Text to display for footnote return links.
googleAnalytics ("")
Google Analytics tracking ID.
hasCJKLanguage (false)
If true, auto-detect Chinese/Japanese/Korean Languages in the content. This will make .Summary and .WordCount behave correctly for CJK languages.
imaging
See Image Processing Config.
languages
See Configure Languages.
languageCode ("")
The site’s language code. It is used in the default RSS template and can be useful for multi-lingual sites.
languageName ("")
The site’s language name.
disableLanguages
See Disable a Language
layoutDir (“layouts”)
The directory from where Hugo reads layouts (templates).
log (false)
Enable logging.
logFile ("")
Log File path (if set, logging enabled automatically).
markup
See Configure Markup.
menu
See Add Non-content Entries to a Menu.
module
Module config see Module Config.
newContentEditor ("")
The editor to use when creating new content.
noChmod (false)
Don’t sync permission mode of files.
noTimes (false)
Don’t sync modification time of files.
paginate (10)
Default number of elements per page in pagination.
paginatePath (“page”)
The path element used during pagination (https://example.com/page/2).
permalinks
See Content Management.
pluralizeListTitles (true)
Pluralize titles in lists.
publishDir (“public”)
The directory to where Hugo will write the final static site (the HTML files etc.).
related
See Related Content.
relativeURLs (false)
Enable this to make all relative URLs relative to content root. Note that this does not affect absolute URLs.
refLinksErrorLevel (“ERROR”)
When using ref or relref to resolve page links and a link cannot resolved, it will be logged with this logg level. Valid values are ERROR (default) or WARNING. Any ERROR will fail the build (exit -1).
refLinksNotFoundURL
URL to be used as a placeholder when a page reference cannot be found in ref or relref. Is used as-is.
rssLimit (unlimited)
Maximum number of items in the RSS feed.
sectionPagesMenu ("")
See “Section Menu for Lazy Bloggers”.
sitemap
Default sitemap configuration.
staticDir (“static”)
A directory or a list of directories from where Hugo reads static files. Also see Module Mounts Config for an alternative way to configure this directory (from Hugo 0.56).
summaryLength (70)
The length of text in words to show in a .Summary.
taxonomies
See Configure Taxonomies.
theme ("")
Theme to use (located by default in /themes/THEMENAME/).
themesDir (“themes”)
The directory where Hugo reads the themes from.
timeout (10000)
Timeout for generating page contents, in milliseconds (defaults to 10 seconds). Note: this is used to bail out of recursive content generation, if your pages are slow to generate (e.g., because they require large image processing or depend on remote contents) you might need to raise this limit.
title ("")
Site title.
titleCaseStyle (“AP”)
See Configure Title Case
uglyURLs (false)
When enabled, creates URL of the form /filename.html instead of /filename/.
verbose (false)
Enable verbose output.
verboseLog (false)
Enable verbose logging.
watch (false)
Watch filesystem for changes and recreate as needed.

If you are developing your site on a *nix machine, here is a handy shortcut for finding a configuration option from the command line:

cd ~/sites/yourhugosite
hugo config | grep emoji

which shows output like

enableemoji: true

配置构建

The build configuration section contains global build-realated configuration options.

config.
     
build:
  useResourceCacheWhen: fallback
[build]
  useResourceCacheWhen = "fallback"
{
   "build": {
      "useResourceCacheWhen": "fallback"
   }
}
useResourceCacheWhen
When to use the cached resources in /resources/_gen for PostCSS and ToCSS. Valid values are never, always and fallback. The last value means that the cache will be tried if PostCSS/extended version is not available.

配置标题案例

Set titleCaseStyle to specify the title style used by the title template function and the automatic section titles in Hugo. It defaults to AP Stylebook for title casing, but you can also set it to Chicago or Go (every word starts with a capital letter).

配置环境变量

HUGO_NUMWORKERMULTIPLIER
Can be set to increase or reduce the number of workers used in parallel processing in Hugo. If not set, the number of logical CPUs will be used.

配置查找顺序

Similar to the template lookup order, Hugo has a default set of rules for searching for a configuration file in the root of your website’s source directory as a default behavior:

  1. ./config.toml
  2. ./config.yaml
  3. ./config.json

In your config file, you can direct Hugo as to how you want your website rendered, control your website’s menus, and arbitrarily define site-wide parameters specific to your project.

示例配置

The following is a typical example of a configuration file. The values nested under params: will populate the .Site.Params variable for use in templates:

config.
     
baseURL: https://yoursite.example.com/
footnoteReturnLinkContents: ↩
params:
  AuthorName: Jon Doe
  GitHubUser: spf13
  ListOfFoo:
  - foo1
  - foo2
  SidebarRecentLimit: 5
  Subtitle: Hugo is Absurdly Fast!
permalinks:
  posts: /:year/:month/:title/
title: My Hugo Site
baseURL = "https://yoursite.example.com/"
footnoteReturnLinkContents = "↩"
title = "My Hugo Site"

[params]
  AuthorName = "Jon Doe"
  GitHubUser = "spf13"
  ListOfFoo = ["foo1", "foo2"]
  SidebarRecentLimit = 5
  Subtitle = "Hugo is Absurdly Fast!"

[permalinks]
  posts = "/:year/:month/:title/"
{
   "baseURL": "https://yoursite.example.com/",
   "footnoteReturnLinkContents": "↩",
   "params": {
      "AuthorName": "Jon Doe",
      "GitHubUser": "spf13",
      "ListOfFoo": [
         "foo1",
         "foo2"
      ],
      "SidebarRecentLimit": 5,
      "Subtitle": "Hugo is Absurdly Fast!"
   },
   "permalinks": {
      "posts": "/:year/:month/:title/"
   },
   "title": "My Hugo Site"
}

配置与环境变量

In addition to the 3 config options already mentioned, configuration key-values can be defined through operating system environment variables.

For example, the following command will effectively set a website’s title on Unix-like systems:

$ env HUGO_TITLE="Some Title" hugo

This is really useful if you use a service such as Netlify to deploy your site. Look at the Hugo docs Netlify configuration file for an example.

Names must be prefixed with HUGO_ and the configuration key must be set in uppercase when setting operating system environment variables.

To set config params, prefix the name with HUGO_PARAMS_

忽略内容文件当渲染

The following statement inside ./config.toml will cause Hugo to ignore content files ending with .foo and .boo when rendering:

ignoreFiles = [ "\\.foo$", "\\.boo$" ]

The above is a list of regular expressions. Note that the backslash (\) character is escaped in this example to keep TOML happy.

配置前页

配置日期

Dates are important in Hugo, and you can configure how Hugo assigns dates to your content pages. You do this by adding a frontmatter section to your config.toml.

The default configuration is:

[frontmatter]
date = ["date", "publishDate", "lastmod"]
lastmod = [":git", "lastmod", "date", "publishDate"]
publishDate = ["publishDate", "date"]
expiryDate = ["expiryDate"]

If you, as an example, have a non-standard date parameter in some of your content, you can override the setting for date:

[frontmatter]
date = ["myDate", ":default"]

The :default is a shortcut to the default settings. The above will set .Date to the date value in myDate if present, if not we will look in date,publishDate, lastmod and pick the first valid date.

In the list to the right, values starting with “:” are date handlers with a special meaning (see below). The others are just names of date parameters (case insensitive) in your front matter configuration. Also note that Hugo have some built-in aliases to the above: lastmod => modified, publishDate => pubdate, published and expiryDate => unpublishdate. With that, as an example, using pubDate as a date in front matter, will, by default, be assigned to .PublishDate.

The special date handlers are:

:fileModTime
Fetches the date from the content file’s last modification timestamp.

An example:

[frontmatter]
lastmod = ["lastmod", ":fileModTime", ":default"]

The above will try first to extract the value for .Lastmod starting with the lastmod front matter parameter, then the content file’s modification timestamp. The last, :default should not be needed here, but Hugo will finally look for a valid date in :git, date and then publishDate.

:filename
Fetches the date from the content file’s filename. For example, 2018-02-22-mypage.md will extract the date 2018-02-22. Also, if slug is not set, mypage will be used as the value for .Slug.

An example:

[frontmatter]
date  = [":filename", ":default"]

The above will try first to extract the value for .Date from the filename, then it will look in front matter parameters date, publishDate and lastly lastmod.

:git
This is the Git author date for the last revision of this content file. This will only be set if --enableGitInfo is set or enableGitInfo = true is set in site config.

配置额外的输出格式

Hugo v0.20 introduced the ability to render your content to multiple output formats (e.g., to JSON, AMP html, or CSV). See Output Formats for information on how to add these values to your Hugo project’s configuration file.

配置文件高速缓存

Since Hugo 0.52 you can configure more than just the cacheDir. This is the default configuration:

[caches]
[caches.getjson]
dir = ":cacheDir/:project"
maxAge = -1
[caches.getcsv]
dir = ":cacheDir/:project"
maxAge = -1
[caches.images]
dir = ":resourceDir/_gen"
maxAge = -1
[caches.assets]
dir = ":resourceDir/_gen"
maxAge = -1
[caches.modules]
dir = ":cacheDir/modules"
maxAge = -1

You can override any of these cache setting in your own config.toml.

关键字解释

:cacheDir
This is the value of the cacheDir config option if set (can also be set via OS env variable HUGO_CACHEDIR). It will fall back to /opt/build/cache/hugo_cache/ on Netlify, or a hugo_cache directory below the OS temp dir for the others. This means that if you run your builds on Netlify, all caches configured with :cacheDir will be saved and restored on the next build. For other CI vendors, please read their documentation. For an CircleCI example, see this configuration.
:project
The base directory name of the current Hugo project. This means that, in its default setting, every project will have separated file caches, which means that when you do hugo --gc you will not touch files related to other Hugo projects running on the same PC.
:resourceDir
This is the value of the resourceDir config option.
maxAge
This is the duration before a cache entry will be evicted, -1 means forever and 0 effectively turns that particular cache off. Uses Go’s time.Duration, so valid values are "10s" (10 seconds), "10m" (10 minutes) and "10h" (10 hours).
dir
The absolute path to where the files for this cache will be stored. Allowed starting placeholders are :cacheDir and :resourceDir (see above).

配置格式规范

  • TOML Spec
  • YAML Spec
  • JSON Spec

See Also

  • Code 切换
  • 数据模板
  • 前面的问题
  • 配置标记
  • jsonify
  • 关于 Hugo
    • 概述
    • Hugo的安全模型
    • Hugo and GDPR
    • 什么是Hugo
    • Hugo 特征
    • 静态的好处
    • 证书
  • 入门
    • 入门概述
    • 快速开始
    • 安装 Hugo
    • 基本用法
    • 目录结构
    • 配置
    • 外部学习资源
  • Hugo 模块
    • Hugo 模块概述
    • 配置模块
    • 使用Hugo模块
    • 主题组件
  • 内容管理
    • 内容管理概述
    • 组织
    • 捆绑页
    • 内容格式
    • 前面的问题
    • 构建选项
    • 网页资源
    • 图像处理
    • 简码
    • 相关内容
    • 章节
    • 内容类型
    • 原型
    • 分类
    • 摘要
    • 链接和交叉引用
    • URL管理
    • 菜单
    • 目录
    • 静态文件
    • 注释
    • 多种语言 和 国际化
    • 语法高亮
  • 模板
    • 模板概述
    • 介绍
    • 模板查找顺序
    • 自定义输出格式
    • 基本模板和模块
    • 列表页面模板
    • 首页模板
    • 章节模板
    • 分类模板
    • 单页模板
    • 内容视图模板
    • 数据模板
    • 部件模板
    • 简码模板
    • 本地文件模板
    • 404页
    • 菜单模板
    • 分页
    • RSS 模板
    • 网站地图模板
    • Robots.txt
    • 内置模板
    • 另类模板
    • 模板调试
  • 函数
    • 函数快速参考
    • .AddDate
    • .Format
    • .Get
    • .GetPage
    • .HasMenuCurrent
    • .IsMenuCurrent
    • .Param
    • .Render
    • .RenderString
    • .Scratch
    • .Unix
    • absLangURL
    • absURL
    • after
    • anchorize
    • append
    • apply
    • base64
    • chomp
    • complement
    • cond
    • countrunes
    • countwords
    • dateFormat
    • default
    • delimit
    • dict
    • echoParam
    • emojify
    • eq
    • errorf and warnf
    • fileExists
    • findRE
    • first
    • float
    • ge
    • getenv
    • group
    • gt
    • hasPrefix
    • highlight
    • htmlEscape
    • htmlUnescape
    • hugo
    • humanize
    • i18n
    • in
    • index
    • int
    • intersect
    • isset
    • jsonify
    • lang.Merge
    • lang.NumFmt
    • last
    • le
    • lower
    • lt
    • markdownify
    • Math
    • md5
    • merge
    • ne
    • now
    • os.Stat
    • partialCached
    • path.Base
    • path.Dir
    • path.Ext
    • path.Join
    • path.Split
    • plainify
    • pluralize
    • print
    • printf
    • println
    • querify
    • range
    • readDir
    • readFile
    • ref
    • reflect.IsMap
    • reflect.IsSlice
    • relLangURL
    • relref
    • relURL
    • replace
    • replaceRE
    • safeCSS
    • safeHTML
    • safeHTMLAttr
    • safeJS
    • safeURL
    • seq
    • sha
    • shuffle
    • singularize
    • slice
    • slicestr
    • sort
    • split
    • string
    • strings.HasSuffix
    • strings.Repeat
    • strings.RuneCount
    • strings.TrimLeft
    • strings.TrimPrefix
    • strings.TrimRight
    • strings.TrimSuffix
    • substr
    • symdiff
    • templates.Exists
    • time
    • title
    • transform.Unmarshal
    • trim
    • truncate
    • union
    • uniq
    • upper
    • urlize
    • urls.Parse
    • where
    • with
    • 图片函数
  • 变量
    • 变量概述
    • 网站变量
    • 简码变量
    • 页面变量
    • 页面方法
    • 分类变量
    • 文件变量
    • 菜单项属性
    • Hugo 变量
    • Git的变量
    • 网站地图变量
  • Hugo 管道
    • Hugo 管道概述
    • Hugo 管道简介
    • SASS / SCSS
    • PostCSS
    • 资产压缩
    • Asset 捆绑
    • 指纹和SRI
    • 来自模板资源
    • 从字符串资源
  • CLI
  • 故障排除
    • 疑难解答
    • FAQ
    • 构建性能
  • 工具
    • 开发工具概述
    • 迁移
    • 入门套件
    • 前端
    • 编辑器插件
    • 搜索
    • 其他的项目
  • 托管和部署
    • 托管和部署概述
    • Hugo 部署
    • 使用Nanobox的主机无关部署
    • AWS Amplify托管
    • Netlify托管
    • Render托管
    • Firebase托管
    • GitHub托管
    • GitLab托管
    • KeyCDN托管
    • Bitbucket托管
    • 使用Wercker部署
    • 使用rsync部署
  • 贡献
    • 贡献Hugo
    • 开发
    • 文档
    • 主题
  • 保养
“配置 Hugo” was last updated: March 24, 2020: 添加翻译 (d6d8ad2)
Improve this page
By the Hugo Authors
Hugo Logo
  • File an Issue
  • Get Help
  • Discuss Source Code
  • @GoHugoIO
  • @spf13
  • @bepsays

Netlify badge

 
 

Hugo Sponsors

Logo for Forestry.io
Logo for Linode
Logo for eSolia
 

The Hugo logos are copyright © Steve Francia 2013–2020.

The Hugo Gopher is based on an original work by Renée French.

  • 新闻
  • 文档
  • 主题
  • 作品展示
  • 社区
  • GitHub
  • 关于 Hugo
  • 入门
  • Hugo 模块
  • 内容管理
  • 模板
  • 函数
  • 变量
  • Hugo 管道
  • CLI
  • 故障排除
  • 工具
  • 托管和部署
  • 贡献
  • 保养