Skip to content

Configuration

Built-in configuration

The following is a minimal configuration built into fasthttpd.

host: localhost
listen: ':8080'
root: ./public
log:
output: stderr
handlers:
'static':
type: fs
indexNames: [index.html]
routes:
- path: /
handler: static

Custom configuration

The following is a configuration that uses most of the current FastHttpd features.

host: localhost
# NOTE: Define listen addr. It is supported ipv6 `[::1]:8080`
listen: ':8080'
root: ./public
# Define fasthttp.Server settings.
server:
name: fasthttpd
readBufferSize: 4096
writeBufferSize: 4096
log:
output: logs/error.log
# NOTE: Flags supports date|time|microseconds
flags: [date, time]
rotation:
maxSize: 100
accessLog:
output: logs/access.log
format: '%h %l %u %t "%r" %>s %b'
rotation:
maxSize: 100
maxBackups: 14
maxAge: 28
compress: true
localTime: true
# Define custom error pages (x matches [0-9])
errorPages:
'404': /err/404.html
'5xx': /err/5xx.html
# Define named filters
filters:
'auth':
type: basicAuth
users:
# WARNING: It is unsafe to define plain secrets. It is recommended for development use only.
- name: fast
secret: httpd
usersFile: ./users.yaml
'cache':
type: header
response:
set:
'Cache-Control': 'private, max-age=3600'
# Define named handlers
handlers:
'static':
type: fs
indexNames: [index.html]
generateIndexPages: false
compress: true
'expvar':
type: expvar
'hello':
type: content
headers:
'Content-Type': 'text/plain; charset=utf-8'
body: |
Hello FastHttpd
# The routes are processed in sequence and interrupted when the status or the handler is specified.
routes:
# Allows GET, POST, HEAD only.
- methods: [PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH]
status: 405
statusMessage: 'Method not allowed'
# Route to /index.html.
- path: /
match: equal
handler: static
# Route to expvar handler.
- path: /expvar
match: equal
handler: expvar
# Redirect to external url with status code 302.
- path: /redirect-external
match: equal
rewrite: http://example.com/
status: 302
# Redirect to internal uri with status code 302 and appendQueryString.
# If "GET /redirect-internal?name=value" is requested then it redirect to "/internal?foo=bar&name=value"
- path: /redirect-internal
match: equal
rewrite: /internal?foo=bar
rewriteAppendQueryString: true
status: 302
# Route to static resources using regexp.
- path: .*\.(js|css|jpg|png|gif|ico)$
match: regexp
filters: [cache]
methods: [GET, HEAD]
handler: static
# Rewrite the path and route to next (no handler and no status).
- path: ^/view/(.+)
match: regexp
rewrite: /view?id=$1
# Other requests are routed to hello with auth filter.
- filters: [auth]
handler: hello
routesCache:
enable: true
expire: 60000
---
host: localhost
listen: ':8443'
ssl:
certFile: ./ssl/localhost.crt
keyFile: ./ssl/localhost.key
handlers:
'backend':
type: proxy
url: 'http://localhost:8080'
routes:
- path: /
handler: backend
---
include: conf.d/*.yaml

Host

host: localhost

Listen

Listen represents the IP adress and port.

listen: ':8080'

Root

Path to the root directory to serve files from. ./ indicates the directory where config.yaml is located.

root: ./public

Server

Server represents settings for fasthttp.Server.

server:
name: fasthttpd
readBufferSize: 4096
writeBufferSize: 4096
readTimeout: 60s
writeTimeout: 60s
KeyDescription
nameServer name for sending in response headers
readBufferSizePer-connection buffer size for requests' reading. This also limits the maximum header size. This also limits the maximum header size. Increase this buffer if your clients send multi-KB RequestURIs and/or multi-KB headers (for example, BIG cookies). Default buffer size is used if not set.
writeBufferSizePer-connection buffer size for responses' writing. Default buffer size is used if not set.
readTimeoutThe amount of time allowed to read the full request including body. The connection's read deadline is reset when the connection opens, or for keep-alive connections after the first byte has been read. By default request read timeout is unlimited. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
writeTimeoutThe maximum duration before timing out writes of the response. It is reset after the request handler has returned. By default response write timeout is unlimited. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

Other string, bool and numbers can be set. See fashttp/server.go for details.

Log

Log represents settings for logging.

log:
output: logs/error.log
# NOTE: Flags supports date|time|microseconds
flags: [date, time]
rotation:
maxSize: 100
maxBackups: 14
maxAge: 28
compress: true
localTime: true
KeyDescription
outputOutput file path. stdout and stderr are special strings that indicate standard output and standard error output, respectively.
flagsFor example, flags [date, time] produce 2009/01/23 01:23:23 message
rotation.maxSizeThe maximum size in megabytes of the log file before it gets rotated. It defaults to 100 megabytes.
rotation.maxBackupsThe maximum number of days to retain old log files based on the timestamp encoded in their filename. Note that a day is defined as 24 hours and may not exactly correspond to calendar days due to daylight savings, leap seconds, etc. The default is not to remove old log files based on age.
rotation.maxAgeThe maximum number of old log files to retain. The default is to retain all old log files (though MaxAge may still cause them to get deleted.)
rotation.compressCompress determines if the rotated log files should be compressed using gzip. The default is not to perform compression.
rotation.localTimeLocalTime determines if the time used for formatting the timestamps in backup files is the computer's local time. The default is to use UTC time.

The rotation is based on natefinch/lumberjack.

AccessLog

AccessLog represents settings for the access logging.

accessLog:
output: logs/access.log
format: '%h %l %u %t "%r" %>s %b'
rotation:
maxSize: 100
maxBackups: 14
maxAge: 28
compress: true
localTime: true
KeyDescription
outputOutput file path. stdout and stderr are special strings that indicate standard output and standard error output, respectively.
formatThe characteristics of the request itself are logged by placing "%" directives in the format string Apache Custom Log Formats
rotation.maxSizeThe maximum size in megabytes of the log file before it gets rotated. It defaults to 100 megabytes.
rotation.maxBackupsThe maximum number of days to retain old log files based on the timestamp encoded in their filename. Note that a day is defined as 24 hours and may not exactly correspond to calendar days due to daylight savings, leap seconds, etc. The default is not to remove old log files based on age.
rotation.maxAgeThe maximum number of old log files to retain. The default is to retain all old log files (though MaxAge may still cause them to get deleted.)
rotation.compressCompress determines if the rotated log files should be compressed using gzip. The default is not to perform compression.
rotation.localTimeLocalTime determines if the time used for formatting the timestamps in backup files is the computer's local time. The default is to use UTC time.

The rotation is based on natefinch/lumberjack.

ErrorPages

# Define custom error pages (x matches [0-9])
errorPages:
'404': /err/404.html
'5xx': /err/5xx.html
KeyDescription
root(Optional) Override root
(http status)Path to custom error page. A http status text can be contain 'x' as wildcard. (eg. '5xx', '40x')

Filters

Any named filter can be defined for filters.

filters:
'auth':
type: basicAuth
users:
# WARNING: It is unsafe to define plain secrets. It is recommended for development use only.
- name: fast
secret: httpd
usersFile: ./users.yaml
'cache':
type: header
response:
set:
'Cache-Control': 'private, max-age=3600'

The following filter types are supported.

  • basicAuth - Provides the basic access authentication.
  • header - Customize request and response headers.

BasicAuth

BasicAuth represents settings for the basic access authentication.

KeyDescription
users[].nameUser name
users[].secretPlain secret
usersFilePath to users file. Refer to testdata/users.yaml

Header represents settings for customizing request and response headers.

KeyDescription
request.setThe header-value mapping. If the same header exists, it is overwritten.
request.addThe header-value mapping
request.delThe list of headers
response.setThe header-value mapping If the same header exists, it is overwritten.
response.addThe header-value mapping
response.delThe list of headers

Handlers

Any named handler can be defined for handlers.

handlers:
'static':
type: fs
indexNames: [index.html]
generateIndexPages: false
compress: true
'hello':
type: content
headers:
'Content-Type': 'text/plain; charset=utf-8'
body: |
Hello FastHttpd
'backend':
type: proxy
url: http://localhost:9000/

The following handler types are supported.

  • fs - Serve static files from the local filesystem
  • content - Serve a in-memory content
  • proxy - Proxy to a backend
  • balancer - Proxy to multiple backends with some algorithm

FS

FS represents settings for request handler serving static files from the local filesystem.

KeyDescription
rootPath to the root directory to serve files from. If omitted, the top-level root is used.
indexNamesList of index file names to try opening during directory access.
generateIndexPagesIndex pages for directories without files matching IndexNames are automatically generated if set.
compressTransparently compresses responses if set to true.

Other string, bool and numbers can be set. See fashttp/fs.go for details.

Content

Content represents settings for serving a in-memory content.

KeyDescription
bodyContent body
headersThe key-value mapping or 'Key: Value' list

Proxy

Proxy represents settings for proxy the single backend.

KeyDescription
urlBackend URL
If you want to proxy multiple backends, use Balancer.

Balancer

Balancer represents settings for proxy the multiple backends. This handler using zehuamama/balancer.

KeyDescription
urlsBackend URLs
algorithmip-hash, consistent-hash, p2c, random, round-robin, least-load, bounded
healthCheckIntervalhealth-check interval (seconds)
If Proxy supports multiple backends, Balancer may be deprecated.
# Balancer example
handlers:
'backend':
type: balancer
algorithm: round-robin
healthCheckInterval: 5
urls:
- http://localhost:9000/
- http://localhost:9001/
- http://localhost:9002/
routes:
- path: /
handler: backend

Routes

The routes are processed in sequence and interrupted when the status or the handler is specified.

routes:
- path: / # The request path
match: prefix # The match type [ prefix | equal | regexp ]
methods: [] # Allow HTTP methods
filters: [] # Filter names
rewrite: '' # The rewrite path
rewriteAppendQueryString: false # Like apache QSA (Query String Append) flag
handler: '' # The handler name
status: 0 # HTTP status
statusMessage: '' # Custom HTTP status message

Routes examples

Rewrite the path and route to backend.

handlers:
'backend':
type: proxy
url: 'http://localhost:8080'
routes:
- path: ^/view/(.+)
match: regexp
rewrite: /view?id=$1
- path: /
handler: backend

Redirect to external url with status code 302.

routes:
- path: /redirect-external
match: equal
rewrite: http://example.com/
status: 302

SSL

ssl:
certFile: ./ssl/localhost.crt
keyFile: ./ssl/localhost.key

SSL auto cert

ssl:
autoCert: true
autoCertCacheDir: /etc/fasthttpd/cache

Virtual hosts

Virtual hosts can be defined in multiple YAML. The first document is the default host.

host: default.example.com
listen: ':80'
---
host: other.example.com
listen: ':80'

Include

include: /etc/fasthttpd/conf.d/*.yaml