1Overview
2=====
3
4CivetWeb is a small and easy to use web server.
5It may be embedded into C/C++ host applications or used as a stand-alone
6server. See `Embedding.md` for information on embedding CivetWeb into
7host applications.
8
9The stand-alone server is self-contained, and does not require any external
10software to run. Some Windows users may need to install the
11[Visual C++ Redistributable](http://www.microsoft.com/en-us/download/details.aspx?id=30679).
12
13
14Installation
15----
16
17On Windows, UNIX and Mac, the CivetWeb stand-alone executable may be started
18from the command line.
19Running `CivetWeb` in a terminal, optionally followed by configuration parameters
20(`CivetWeb [OPTIONS]`) or a configuration file name (`CivetWeb [config_file_name]`),
21starts the web server.
22
23For UNIX and Mac, CivetWeb does not detach from the terminal.
24Pressing `Ctrl-C` keys will stop the server.
25
26On Windows, CivetWeb iconifies itself to the system tray icon when started.
27Right-clicking on the icon pops up a menu, where it is possible to stop
28CivetWeb, configure it, or install it as Windows service.
29
30When started without options, the server exposes the local directory at
31[http](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) port 8080.
32Thus, the easiest way to share a folder on Windows is to copy `CivetWeb.exe`
33to this folder, double-click the exe, and launch a browser at
34[http://localhost:8080](http://localhost:8080). Note that 'localhost' should
35be changed to a machine's name if a folder is accessed from another computer.
36
37When started, CivetWeb first searches for the configuration file.
38If a configuration file is specified explicitly in the command line, i.e.
39`CivetWeb path_to_config_file`, then the specified configuration file is used.
40Otherwise, CivetWeb will search for the file `CivetWeb.conf` in the same directory that
41the executable is located, and use it. This configuration file is optional.
42
43The configuration file is a sequence of lines, each line containing one
44command line argument name and the corresponding value.
45Empty lines, and lines beginning with `#`, are ignored.
46Here is the example of a `CivetWeb.conf` file:
47
48    document_root c:\www
49    listening_ports 80,443s
50    ssl_certificate c:\CivetWeb\ssl_cert.pem
51
52When a configuration file is used, additional command line arguments may
53override the configuration file settings.
54All command line arguments must start with `-`.
55
56For example: The above `CivetWeb.conf` file is used, and CivetWeb started as
57`CivetWeb -document_root D:\web`. Then the `D:\web` directory will be served
58as document root, because command line options take priority over the
59configuration file. The configuration options section below provides a good
60overview of CivetWeb features.
61
62Note that configuration options on the command line must start with `-`,
63but their names are the same as in the config file. All option names are
64listed in the next section. Thus, the following two setups are equivalent:
65
66    # Using command line arguments
67    $ CivetWeb -listening_ports 1234 -document_root /var/www
68
69    # Using config file
70    $ cat CivetWeb.conf
71    listening_ports 1234
72    document_root /var/www
73    $ CivetWeb
74
75CivetWeb can also be used to modify `.htpasswd` passwords files:
76
77    CivetWeb -A <htpasswd_file> <realm> <user> <passwd>
78
79
80Configuration Options
81----
82
83Below is a list of configuration options understood by CivetWeb.
84Every option is followed by it's default value. If a default value is not
85present, then the default is empty.
86
87## Pattern matching in configuration options
88
89CivetWeb uses shell-like glob patterns for several configuration options,
90e.g., CGI, SSI and Lua script files are recognized by the file name pattern.
91Pattern match starts at the beginning of the string, so essentially
92patterns are prefix patterns. Syntax is as follows:
93
94     **      Matches everything
95     *       Matches everything but slash character, '/'
96     ?       Matches any character
97     $       Matches the end of the string
98     |       Matches if pattern on the left side or the right side matches.
99
100All other characters in the pattern match themselves. Examples:
101
102    **.cgi$      Any string that ends with .cgi
103    /foo         Any string that begins with /foo
104    **a$|**b$    Any string that ends with a or b
105
106
107## Options from `civetweb.c`
108
109The following options are supported in `civetweb.c`. They can be used for
110the stand-alone executable as well as for applications embedding CivetWeb.
111The stand-alone executable supports some additional options: see *Options from `main.c`*.
112The options are explained in alphabetic order - for a quick start, check
113*document\_root*, *listening\_ports*, *error\_log\_file* and (for HTTPS) *ssl\_certificate*.
114
115### access\_control\_allow\_headers `*`
116Access-Control-Allow-Headers header field, used for cross-origin resource
117sharing (CORS) pre-flight requests.
118See the [Wikipedia page on CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
119
120If set to an empty string, pre-flights will not allow additional headers.
121If set to "*", the pre-flight will allow whatever headers have been requested.
122If set to a comma separated list of valid HTTP headers, the pre-flight will return
123exactly this list as allowed headers.
124If set in any other way, the result is unspecified.
125
126### access\_control\_allow\_methods `*`
127Access-Control-Allow-Methods header field, used for cross-origin resource
128sharing (CORS) pre-flight requests.
129See the [Wikipedia page on CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
130
131If set to an empty string, pre-flights will not be supported directly by the server,
132but scripts may still support pre-flights by handling the OPTIONS method properly.
133If set to "*", the pre-flight will allow whatever method has been requested.
134If set to a comma separated list of valid HTTP methods, the pre-flight will return
135exactly this list as allowed method.
136If set in any other way, the result is unspecified.
137
138### access\_control\_allow\_origin `*`
139Access-Control-Allow-Origin header field, used for cross-origin resource
140sharing (CORS).
141See the [Wikipedia page on CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
142
143### access\_control\_list
144An Access Control List (ACL) allows restrictions to be put on the list of IP
145addresses which have access to the web server. In the case of the CivetWeb
146web server, the ACL is a comma separated list of IP subnets, where each
147subnet is pre-pended by either a `-` or a `+` sign. A plus sign means allow,
148where a minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
149this means to deny only that single IP address.
150
151Subnet masks may vary from 0 to 32, inclusive. The default setting is to allow
152all accesses. On each request the full list is traversed, and
153the last match wins. Examples:
154
155    -0.0.0.0/0,+192.168/16    deny all accesses, only allow 192.168/16 subnet
156
157To learn more about subnet masks, see the
158[Wikipedia page on Subnetwork](http://en.wikipedia.org/wiki/Subnetwork).
159
160### access\_log\_file
161Path to a file for access logs. Either full path, or relative to the current
162working directory. If absent (default), then accesses are not logged.
163
164### additional\_header
165Send additional HTTP response header line for every request.
166The full header line including key and value must be specified, excluding the carriage return line feed.
167
168Example (used as command line option):
169`-additional_header "X-Frame-Options: SAMEORIGIN"`
170
171This option can be specified multiple times. All specified header lines will be sent.
172
173### allow\_index\_script\_resource `no`
174Index scripts (like `index.cgi` or `index.lua`) may have script handled resources.
175
176It this feature is activated, that /some/path/file.ext might be handled by:
177  1. /some/path/file.ext (with PATH\_INFO='/', if ext = cgi)
178  2. /some/path/index.lua with mg.request\_info.path\_info='/file.ext'
179  3. /some/path/index.cgi with PATH\_INFO='/file.ext'
180  4. /some/path/index.php with PATH\_INFO='/file.ext'
181  5. /some/index.lua with mg.request\_info.path\_info=='/path/file.ext'
182  6. /some/index.cgi with PATH\_INFO='/path/file.ext'
183  7. /some/index.php with PATH\_INFO='/path/file.ext'
184  8. /index.lua with mg.request\_info.path\_info=='/some/path/file.ext'
185  9. /index.cgi with PATH\_INFO='/some/path/file.ext'
186  10. /index.php with PATH\_INFO='/some/path/file.ext'
187
188Note: This example is valid, if the default configuration values for
189`index_files`, `cgi_pattern` and `lua_script_pattern` are used,
190and the server is built with CGI and Lua support enabled.
191
192If this feature is not activated, only the first file (/some/path/file.cgi) will be accepted.
193
194Note: This parameter affects only index scripts. A path like /here/script.cgi/handle/this.ext
195will call /here/script.cgi with PATH\_INFO='/handle/this.ext', no matter if this option is set to `yes` or `no`.
196
197This feature can be used to completely hide the script extension from the URL.
198
199### allow\_sendfile\_call `yes`
200This option can be used to enable or disable the use of the Linux `sendfile` system call.
201It is only available for Linux systems and only affecting HTTP (not HTTPS) connections
202if `throttle` is not enabled.
203While using the `sendfile` call will lead to a performance boost for HTTP connections,
204this call may be broken for some file systems and some operating system versions.
205
206### authentication\_domain `mydomain.com`
207Authorization realm used for HTTP digest authentication. This domain is
208used in the encoding of the `.htpasswd` authorization files as well.
209Changing the domain retroactively will render the existing passwords useless.
210
211### case\_sensitive `no`
212This option can be uset to enable case URLs for Windows servers.
213It is only available for Windows systems.  Windows file systems are not case sensitive,
214but they still store the file name including case.
215If this option is set to `yes`, the comparison for URIs and Windows file names will be case sensitive.
216
217### cgi\_environment
218Extra environment variables to be passed to the CGI script in
219addition to standard ones. The list must be comma-separated list
220of name=value pairs, like this: `VARIABLE1=VALUE1,VARIABLE2=VALUE2`.
221
222### cgi\_interpreter
223Path to an executable to use as CGI interpreter for __all__ CGI scripts
224regardless of the script file extension. If this option is not set (which is
225the default), CivetWeb looks at first line of a CGI script,
226[shebang line](http://en.wikipedia.org/wiki/Shebang_(Unix\)), for an
227interpreter (not only on Linux and Mac but also for Windows).
228
229For example, if both PHP and Perl CGIs are used, then
230`#!/path/to/php-cgi.exe` and `#!/path/to/perl.exe` must be first lines of the
231respective CGI scripts. Note that paths should be either full file paths,
232or file paths relative to the current working directory of the CivetWeb
233server. If CivetWeb is started by mouse double-click on Windows, the current
234working directory is the directory where the CivetWeb executable is located.
235
236If all CGIs use the same interpreter, for example they are all PHP, it is
237more efficient to set `cgi_interpreter` to the path to `php-cgi.exe`.
238The shebang line in the CGI scripts can be omitted in this case.
239Note that PHP scripts must use `php-cgi.exe` as executable, not `php.exe`.
240
241### cgi\_pattern `**.cgi$|**.pl$|**.php$`
242All files that match `cgi_pattern` are treated as CGI files. The default pattern
243allows CGI files be anywhere. To restrict CGIs to a certain directory,
244use `/path/to/cgi-bin/**.cgi` as the pattern. Note that the full file path is
245matched against the pattern, not the URI.
246
247### cgi\_timeout\_ms
248Maximum allowed runtime for CGI scripts.  CGI processes are terminated by
249the server after this time.  The default is "no timeout", so scripts may
250run or block for undefined time.
251
252### decode\_url `yes`
253URL encoded request strings are decoded in the server, unless it is disabled
254by setting this option to `no`.
255
256### document\_root `.`
257A directory to serve. By default, the current working directory is served.
258The current directory is commonly referenced as dot (`.`).
259It is recommended to use an absolute path for document\_root, in order to
260avoid accidentally serving the wrong directory.
261
262### enable\_auth\_domain\_check `yes`
263When using absolute URLs, verify the host is identical to the authentication\_domain.
264If enabled, requests to absolute URLs will only be processed
265if they are directed to the domain. If disabled, absolute URLs to any host
266will be accepted.
267
268### enable\_directory\_listing `yes`
269Enable directory listing, either `yes` or `no`.
270
271### enable\_keep\_alive `no`
272Enable connection keep alive, either `yes` or `no`.
273
274Allows clients to reuse TCP connection for subsequent HTTP requests,
275which improves performance.
276For this to work when using request handlers it is important to add the
277correct Content-Length HTTP header for each request. If this is forgotten the
278client will time out.
279
280Note: If you set keep\_alive to `yes`, you should set keep\_alive\_timeout\_ms
281to some value > 0 (e.g. 500). If you set keep\_alive to `no`, you should set
282keep\_alive\_timeout\_ms to 0. Currently, this is done as a default value,
283but this configuration is redundant. In a future version, the keep\_alive
284configuration option might be removed and automatically set to `yes` if
285a timeout > 0 is set.
286
287### enable\_websocket\_ping\_pong `no`
288If this configuration value is set to `yes`, the server will send a
289websocket PING message to a websocket client, once the timeout set by
290websocket\_timeout\_ms expires. Clients (Web browsers) supporting this
291feature will reply with a PONG message.
292
293If this configuration value is set to `no`, the websocket server will
294close the connection, once the timeout expires.
295
296Note: This configuration value only exists, if the server has been built
297with websocket support enabled.
298
299### error\_log\_file
300Path to a file for error logs. Either full path, or relative to the current
301working directory. If absent (default), then errors are not logged.
302
303### error\_pages
304This option may be used to specify a directory for user defined error pages.
305To specify a directory, make sure the name ends with a backslash (Windows)
306or slash (Linux, MacOS, ...).
307The error pages may be specified for an individual http status code (e.g.,
308404 - page requested by the client not found), a group of http status codes
309(e.g., 4xx - all client errors) or all errors. The corresponding error pages
310must be called error404.ext, error4xx.ext or error.ext, whereas the file
311extension may be one of the extensions specified for the index_files option.
312See the [Wikipedia page on HTTP status codes](http://en.wikipedia.org/wiki/HTTP_status_code).
313
314### extra\_mime\_types
315Extra mime types, in the form `extension1=type1,exten-sion2=type2,...`.
316See the [Wikipedia page on Internet media types](http://en.wikipedia.org/wiki/Internet_media_type).
317Extension must include a leading dot. Example:
318`.cpp=plain/text,.java=plain/text`
319
320### global\_auth\_file
321Path to a global passwords file, either full path or relative to the current
322working directory. If set, per-directory `.htpasswd` files are ignored,
323and all requests are authorized against that file.
324
325The file has to include the realm set through `authentication_domain` and the
326password in digest format:
327
328    user:realm:digest
329    test:test.com:ce0220efc2dd2fad6185e1f1af5a4327
330
331Password files may be generated using `CivetWeb -A` as explained above, or
332online tools e.g. [this generator](http://www.askapache.com/online-tools/htpasswd-generator).
333
334### hide\_files\_patterns
335A pattern for the files to hide. Files that match the pattern will not
336show up in directory listing and return `404 Not Found` if requested. Pattern
337must be for a file name only, not including directory names. Example:
338
339    CivetWeb -hide_files_patterns secret.txt|**.hide
340
341Note: hide\_file\_patterns uses the pattern described above. If you want to
342hide all files with a certain extension, make sure to use **.extension
343(not just *.extension).
344
345### index\_files `index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php`
346Comma-separated list of files to be treated as directory index files.
347If more than one matching file is present in a directory, the one listed to the left
348is used as a directory index.
349
350In case built-in Lua support has been enabled, `index.lp,index.lsp,index.lua`
351are additional default index files, ordered before `index.cgi`.
352
353### keep\_alive\_timeout\_ms `500` or `0`
354Idle timeout between two requests in one keep-alive connection.
355If keep alive is enabled, multiple requests using the same connection
356are possible. This reduces the overhead for opening and closing connections
357when loading several resources from one server, but it also blocks one port
358and one thread at the server during the lifetime of this connection.
359Unfortunately, browsers do not close the keep-alive connection after loading
360all resources required to show a website.
361The server closes a keep-alive connection, if there is no additional request
362from the client during this timeout.
363
364Note: if enable\_keep\_alive is set to `no` the value of
365keep\_alive\_timeout\_ms should be set to `0`, if enable\_keep\_alive is set
366to `yes`, the value of keep\_alive\_timeout\_ms must be >0.
367Currently keep\_alive\_timeout\_ms is ignored if enable\_keep\_alive is no,
368but future versions may drop the enable\_keep\_alive configuration value and
369automatically use keep-alive if keep\_alive\_timeout\_ms is not 0.
370
371### linger\_timeout\_ms
372Set TCP socket linger timeout before closing sockets (SO\_LINGER option).
373The configured value is a timeout in milliseconds. Setting the value to 0
374will yield in abortive close (if the socket is closed from the server side).
375Setting the value to -1 will turn off linger.
376If the value is not set (or set to -2), CivetWeb will not set the linger
377option at all.
378
379Note: For consistency with other timeout configurations, the value is
380configured in milliseconds. However, the TCP socket layer usually only
381offers a timeout in seconds, so the value should be an integer multiple
382of 1000.
383
384### lua\_background\_script
385Experimental feature, and subject to change.
386Run a Lua script in the background, independent from any connection.
387The script is started before network access to the server is available.
388It can be used to prepare the document root (e.g., update files, compress
389files, ...), check for external resources, remove old log files, etc.
390
391The Lua state remains open until the server is stopped.
392In the future, some callback functions will be available to notify the
393script on changes of the server state. See example lua script :
394[background.lua](https://github.com/civetweb/civetweb/blob/master/test/background.lua).
395
396Additional functions available in background script :
397sleep, root path, script name, is terminated
398
399### lua\_background\_script\_params `param1=1,param2=2`
400Can add dynamic parameters to background script.
401Parameters mapped to global 'mg' table 'params' field.
402
403### lua\_preload\_file
404This configuration option can be used to specify a Lua script file, which
405is executed before the actual web page script (Lua script, Lua server page
406or Lua websocket). It can be used to modify the Lua environment of all web
407page scripts, e.g., by loading additional libraries or defining functions
408required by all scripts.
409It may be used to achieve backward compatibility by defining obsolete
410functions as well.
411
412### lua\_script\_pattern `"**.lua$`
413A pattern for files that are interpreted as Lua scripts by the server.
414In contrast to Lua server pages, Lua scripts use plain Lua syntax.
415An example can be found in the test directory.
416
417### lua\_server\_page\_pattern `**.lp$|**.lsp$`
418Files matching this pattern are treated as Lua server pages.
419In contrast to Lua scripts, the content of a Lua server pages is delivered
420directly to the client. Lua script parts are delimited from the standard
421content by including them between <? and ?> tags.
422An example can be found in the test directory.
423
424### lua\_websocket\_pattern `"**.lua$`
425A pattern for websocket script files that are interpreted as Lua scripts by the server.
426
427### listening\_ports `8080`
428Comma-separated list of ports to listen on. If the port is SSL, a
429letter `s` must be appended, for example, `80,443s` will open
430port 80 and port 443, and connections on port 443 will be SSL-ed.
431For non-SSL ports, it is allowed to append letter `r`, meaning 'redirect'.
432Redirect ports will redirect all their traffic to the first configured
433SSL port. For example, if `listening_ports` is `80r,443s`, then all
434HTTP traffic coming at port 80 will be redirected to HTTPS port 443.
435
436It is possible to specify an IP address to bind to. In this case,
437an IP address and a colon must be pre-pended to the port number.
438For example, to bind to a loopback interface on port 80 and to
439all interfaces on HTTPS port 443, use `127.0.0.1:80,443s`.
440
441If the server is built with IPv6 support, `[::]:8080` can be used to
442listen to IPv6 connections to port 8080. IPv6 addresses of network
443interfaces can be specified as well,
444e.g. `[::1]:8080` for the IPv6 loopback interface.
445
446[::]:80 will bind to port 80 IPv6 only. In order to use port 80 for
447all interfaces, both IPv4 and IPv6, use either the configuration
448`80,[::]:80` (create one socket for IPv4 and one for IPv6 only),
449or `+80` (create one socket for both, IPv4 and IPv6).
450The `+` notation to use IPv4 and IPv6 will only work if no network
451interface is specified. Depending on your operating system version
452and IPv6 network environment, some configurations might not work
453as expected, so you have to test to find the configuration most
454suitable for your needs. In case `+80` does not work for your
455environment, you need to use `80,[::]:80`.
456
457It is possible to use network interface addresses (e.g., `192.0.2.3:80`,
458`[2001:0db8::1234]:80`). To get a list of available network interface
459addresses, use `ipconfig` (in a `cmd` window in Windows) or `ifconfig`
460(in a Linux shell).
461Alternatively, you could use the hostname for an interface. Check the
462hosts file of your operating system for a proper hostname
463(for Windows, usually found in C:\Windows\System32\drivers\etc\,
464for most Linux distributions: /etc/hosts). E.g., to bind the IPv6
465local host, you could use `ip6-localhost:80`. This translates to
466`[::1]:80`. Beside the hosts file, there are several other name
467resolution services. Using your hostname might bind you to the
468localhost or an external interface. You could also try `hostname.local`,
469if the proper network services are installed (Zeroconf, mDNS, Bonjour,
470Avahi). When using a hostname, you need to test in your particular network
471environment - in some cases, you might need to resort to a fixed IP address.
472
473If you want to use an ephemeral port (i.e. let the operating system choose
474a port number), use `0` for the port number. This will make it necessary to
475communicate the port number to clients via other means, for example mDNS
476(or Zeroconf, Bonjour or Avahi).
477
478### max\_request\_size `16384`
479Size limit for HTTP request headers and header data returned from CGI scripts, in Bytes.
480A buffer of the configured size is pre allocated for every worker thread.
481max\_request\_size limits the HTTP header, including query string and cookies,
482but it does not affect the HTTP body length.
483The server has to read the entire header from a client or from a CGI script,
484before it is able to process it. In case the header is longer than max\_request\_size,
485the request is considered as invalid or as DoS attack.
486The configuration value is approximate, the real limit might be a few bytes off.
487The minimum is 1024 (1 kB).
488
489### num\_threads `50`
490Number of worker threads. CivetWeb handles each incoming connection in a
491separate thread. Therefore, the value of this option is effectively the number
492of concurrent HTTP connections CivetWeb can handle.
493
494### protect\_uri
495Comma separated list of URI=PATH pairs, specifying that given
496URIs must be protected with password files specified by PATH.
497All Paths must be full file paths.
498
499### put\_delete\_auth\_file
500Passwords file for PUT and DELETE requests. Without a password file, it will not
501be possible to PUT new files to the server or DELETE existing ones. PUT and
502DELETE requests might still be handled by Lua scripts and CGI paged.
503
504### request\_timeout\_ms `30000`
505Timeout for network read and network write operations, in milliseconds.
506If a client intends to keep long-running connection, either increase this
507value or (better) use keep-alive messages.
508
509### run\_as\_user
510Switch to given user credentials after startup. Usually, this option is
511required when CivetWeb needs to bind on privileged ports on UNIX. To do
512that, CivetWeb needs to be started as root. From a security point of view,
513running as root is not advisable, therefore this option can be used to drop
514privileges. Example:
515
516    civetweb -listening_ports 80 -run_as_user webserver
517
518### ssi\_pattern `**.shtml$|**.shtm$`
519All files that match `ssi_pattern` are treated as Server Side Includes (SSI).
520
521SSI is a simple interpreted server-side scripting language which is most
522commonly used to include the contents of another file in a web page.
523It can be useful when it is desirable to include a common piece
524of code throughout a website, for example, headers and footers.
525
526In order for a webpage to recognize an SSI-enabled HTML file, the filename
527should end with a special extension, by default the extension should be
528either `.shtml` or `.shtm`. These extensions may be changed using the
529`ssi_pattern` option.
530
531Unknown SSI directives are silently ignored by CivetWeb. Currently, two SSI
532directives are supported, `<!--#include ...>` and
533`<!--#exec "command">`. Note that the `<!--#include ...>` directive supports
534three path specifications:
535
536    <!--#include virtual="path">  Path is relative to web server root
537    <!--#include abspath="path">  Path is absolute or relative to
538                                  web server working dir
539    <!--#include file="path">,    Path is relative to current document
540    <!--#include "path">
541
542The `include` directive may be used to include the contents of a file or the
543result of running a CGI script. The `exec` directive is used to execute a
544command on a server, and show the output that would have been printed to
545stdout (the terminal window) otherwise. Example:
546
547    <!--#exec "ls -l" -->
548
549For more information on Server Side Includes, take a look at the Wikipedia:
550[Server Side Includes](http://en.wikipedia.org/wiki/Server_Side_Includes)
551
552### ssl\_ca\_path
553Name of a directory containing trusted CA certificates. Each file in the
554directory must contain only a single CA certificate. The files must be named
555by the subject name’s hash and an extension of “.0”. If there is more than one
556certificate with the same subject name they should have extensions ".0", ".1",
557".2" and so on respectively.
558
559### ssl\_ca\_file
560Path to a .pem file containing trusted certificates. The file may contain
561more than one certificate.
562
563### ssl\_certificate
564Path to the SSL certificate file. This option is only required when at least
565one of the `listening\_ports` is SSL. The file must be in PEM format,
566and it must have both, private key and certificate, see for example
567[ssl_cert.pem](https://github.com/civetweb/civetweb/blob/master/resources/ssl_cert.pem)
568A description how to create a certificate can be found in doc/OpenSSL.md
569
570### ssl\_certificate\_chain
571Path to an SSL certificate chain file. As a default, the ssl\_certificate file is used.
572
573### ssl\_cipher\_list
574List of ciphers to present to the client. Entries should be separated by
575colons, commas or spaces.
576
577    ALL           All available ciphers
578    ALL:!eNULL    All ciphers excluding NULL ciphers
579    AES128:!MD5   AES 128 with digests other than MD5
580
581See [this entry](https://www.openssl.org/docs/manmaster/apps/ciphers.html) in
582OpenSSL documentation for full list of options and additional examples.
583
584### ssl\_default\_verify\_paths `yes`
585Loads default trusted certificates locations set at openssl compile time.
586
587### ssl\_protocol\_version `0`
588Sets the minimal accepted version of SSL/TLS protocol according to the table:
589
590Protocols | Value
591------------ | -------------
592SSL2+SSL3+TLS1.0+TLS1.1+TLS1.2  | 0
593SSL3+TLS1.0+TLS1.1+TLS1.2  | 1
594TLS1.0+TLS1.1+TLS1.2 | 2
595TLS1.1+TLS1.2 | 3
596TLS1.2 | 4
597
598More recent versions of OpenSSL include support for TLS version 1.3.
599To use TLS1.3 only, set ssl\_protocol\_version to 5.
600
601### ssl\_short\_trust `no`
602Enables the use of short lived certificates. This will allow for the certificates
603and keys specified in `ssl_certificate`, `ssl_ca_file` and `ssl_ca_path` to be
604exchanged and reloaded while the server is running.
605
606In an automated environment it is advised to first write the new pem file to
607a different filename and then to rename it to the configured pem file name to
608increase performance while swapping the certificate.
609
610Disk IO performance can be improved when keeping the certificates and keys stored
611on a tmpfs (linux) on a system with very high throughput.
612
613### ssl\_verify\_depth `9`
614Sets maximum depth of certificate chain. If client's certificate chain is longer
615than the depth set here connection is refused.
616
617### ssl\_verify\_peer `no`
618Enable client's certificate verification by the server.
619
620### static\_file\_max\_age `3600`
621Set the maximum time (in seconds) a cache may store a static files.
622
623This option will set the `Cache-Control: max-age` value for static files.
624Dynamically generated content, i.e., content created by a script or callback,
625must send cache control headers by themselves.
626
627A value >0 corresponds to a maximum allowed caching time in seconds.
628This value should not exceed one year (RFC 2616, Section 14.21).
629A value of 0 will send "do not cache" headers for all static files.
630For values <0 and values >31622400, the behaviour is undefined.
631
632### strict\_transport\_security\_max\_age
633
634Set the `Strict-Transport-Security` header, and set the `max-age` value.
635This instructs web browsers to interact with the server only using HTTPS,
636never by HTTP. If set, it will be sent for every request handled directly
637by the server, except scripts (CGI, Lua, ..) and callbacks. They must
638send HTTP headers on their own.
639
640The time is specified in seconds. If this configuration is not set,
641or set to -1, no `Strict-Transport-Security` header will be sent.
642For values <-1 and values >31622400, the behaviour is undefined.
643
644### tcp\_nodelay `0`
645Enable TCP_NODELAY socket option on client connections.
646
647If set the socket option will disable Nagle's algorithm on the connection
648which means that packets will be sent as soon as possible instead of waiting
649for a full buffer or timeout to occur.
650
651    0    Keep the default: Nagel's algorithm enabled
652    1    Disable Nagel's algorithm for all sockets
653
654### throttle
655Limit download speed for clients.  `throttle` is a comma-separated
656list of key=value pairs, where key could be:
657
658    *                   limit speed for all connections
659    x.x.x.x/mask        limit speed for specified subnet
660    uri_prefix_pattern  limit speed for given URIs
661
662The value is a floating-point number of bytes per second, optionally
663followed by a `k` or `m` character, meaning kilobytes and
664megabytes respectively. A limit of 0 means unlimited rate. The
665last matching rule wins. Examples:
666
667    *=1k,10.0.0.0/8=0   limit all accesses to 1 kilobyte per second,
668                        but give connections the from 10.0.0.0/8 subnet
669                        unlimited speed
670
671    /downloads/=5k      limit accesses to all URIs in `/downloads/` to
672                        5 kilobytes per second. All other accesses are unlimited
673
674### url\_rewrite\_patterns
675Comma-separated list of URL rewrites in the form of
676`uri_pattern=file_or_directory_path`. When CivetWeb receives any request,
677it constructs the file name to show by combining `document_root` and the URI.
678However, if the rewrite option is used and `uri_pattern` matches the
679requested URI, then `document_root` is ignored. Instead,
680`file_or_directory_path` is used, which should be a full path name or
681a path relative to the web server's current working directory. Note that
682`uri_pattern`, as all CivetWeb patterns, is a prefix pattern.
683
684This makes it possible to serve many directories outside from `document_root`,
685redirect all requests to scripts, and do other tricky things. For example,
686to redirect all accesses to `.doc` files to a special script, do:
687
688    CivetWeb -url_rewrite_patterns **.doc$=/path/to/cgi-bin/handle_doc.cgi
689
690Or, to imitate support for user home directories, do:
691
692    CivetWeb -url_rewrite_patterns /~joe/=/home/joe/,/~bill=/home/bill/
693
694### websocket\_root
695In case CivetWeb is built with Lua and websocket support, Lua scripts may
696be used for websockets as well. Since websockets use a different URL scheme
697(ws, wss) than other http pages (http, https), the Lua scripts used for
698websockets may also be served from a different directory. By default,
699the document\_root is used as websocket\_root as well.
700
701### websocket\_timeout\_ms
702Timeout for network read and network write operations for websockets, WS(S),
703in milliseconds. If this value is not set, the value of request\_timeout\_ms
704is used for HTTP(S) as well as for WS(S). In case websocket\_timeout\_ms is
705set, HTTP(S) and WS(S) can use different timeouts.
706
707Note: This configuration value only exists, if the server has been built
708with websocket support enabled.
709
710
711## Options from `main.c`
712
713The following options are supported in `main.c`, the additional source file for
714the stand-alone executable. These options are not supported by other applications
715embedding `civetweb.c`, unless they are added explicitly.
716
717### title
718Use the configured string as a server name.  For Windows, this will be shown as
719the window title.
720
721### icon
722For Windows, show this icon file in the systray, replacing the CivetWeb standard
723icon.  This option has no effect for Linux.
724
725### website
726For Windows, use this website as a link in the systray, replacing the default
727link for CivetWeb.
728
729
730### add\_domain
731Option to load an additional configuration file, specifying an additional domain
732to host.  To add multiple additional domains, use the add\_domain option
733multiple times with one configuration file for each domain.
734A domain configuration file may have the same options as the main server, with
735some exceptions.  The options are passed to the `mg_start_domain` API function.
736
737
738Scripting
739----
740
741# Lua Scripts and Lua Server Pages
742Pre-built Windows and Mac CivetWeb binaries have built-in Lua scripting
743support as well as support for Lua Server Pages.
744
745Lua scripts (default extension: *.lua) use plain Lua syntax.
746The body of the script file is not sent directly to the client,
747the Lua script must send header and content of the web page by calling
748the function mg.write(text).
749
750Lua Server Pages (default extensions: *.lsp, *.lp) are html pages containing
751script elements similar to PHP, using the Lua programming language instead of
752PHP. Lua script elements must be enclosed in `<?  ?>` blocks, and can appear
753anywhere on the page. Furthermore, Lua Server Pages offer the opportunity to
754insert the content of a variable by enclosing the Lua variable name in
755`<?=  ?>` blocks, similar to PHP.
756For example, to print the current weekday name and the URI of the current
757page, one can write:
758
759    <p>
760      <span>Today is:</span>
761      <? mg.write(os.date("%A")) ?>
762    </p>
763    <p>
764      URI is <?=mg.request_info.uri?>
765    </p>
766
767From version 1.11, CivetWeb supports "Kepler Syntax" in addition to the
768traditional Lua pages syntax of CivetWeb. Kepler Syntax uses `<?lua ?>`
769or `<% %>` blocks for script elements (corresponding to `<? ?>` above)
770and `<?lua= ?>` or `<%= %>` for variable content (corresponding to `<?= ?>`).
771
772    <ul>
773       <% for key, value in pairs(mg.request_info) do %>
774       <li> <%= key %>: <%= value %> </li>
775       <% end %>
776    </ul>
777
778Currently the extended "Kepler Syntax" is available only for HTML (see
779note on HTTP headers below).
780
781Lua is known for it's speed and small size. The default Lua version for
782CivetWeb is Lua 5.2.4. The documentation for it can be found in the
783[Lua 5.2 reference manual](http://www.lua.org/manual/5.2/). However,
784CivetWeb can be built with Lua 5.1, 5.2, 5.3, 5.4 (currently pre-release)
785and LuaJIT.
786
787Note that this example uses function `mg.write()`, which sends data to the
788web client. Using `mg.write()` is the way to generate web content from inside
789Lua code. In addition to `mg.write()`, all standard Lua library functions
790are accessible from the Lua code (please check the reference manual for
791details). Lua functions working on files (e.g., `io.open`) use a path
792relative to the working path of the CivetWeb process. The web server content
793is located in the path `mg.document_root`.
794Information on the request is available in the `mg.request_info`
795object, like the request method, all HTTP headers, etcetera.
796
797[page2.lua](https://github.com/civetweb/civetweb/blob/master/test/page2.lua)
798is an example for a plain Lua script.
799
800[page2.lp](https://github.com/civetweb/civetweb/blob/master/test/page2.lp)
801is an example for a Lua Server Page.
802
803[page4kepler.lp](https://github.com/civetweb/civetweb/blob/master/test/page4kepler.lp)
804is a Lua Server Page showing "Kepler Syntax" in addition to traditional CivetWeb
805Lua Server Pages syntax.
806
807These examples show the content of the `mg.request_info` object as the page
808content. Please refer to `struct mg_request_info` definition in
809[CivetWeb.h](https://github.com/civetweb/civetweb/blob/master/include/civetweb.h)
810to see additional information on the elements of the `mg.request_info` object.
811
812CivetWeb also provides access to the [SQlite3 database](http://www.sqlite.org/)
813through the [LuaSQLite3 interface](http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki)
814in Lua. Examples are given in
815[page.lua](https://github.com/civetweb/civetweb/blob/master/test/page.lua) and
816[page.lp](https://github.com/civetweb/civetweb/blob/master/test/page.lp).
817
818
819CivetWeb exports the following functions to Lua:
820
821mg (table):
822
823    mg.read()                   -- reads a chunk from POST data, returns it as a string
824    mg.write(str)               -- writes string to the client
825    mg.include(filename, [pathtype]) -- include another Lua Page file (Lua Pages only)
826                                -- pathtype can be "abs", "rel"/"file" or "virt[ual]"
827                                -- like defined for SSI #include
828    mg.redirect(uri)            -- internal redirect to a given URI
829    mg.onerror(msg)             -- error handler, can be overridden
830    mg.version                  -- a string that holds CivetWeb version
831    mg.document_root            -- a string that holds the document root directory
832    mg.auth_domain              -- a string that holds the HTTP authentication domain
833    mg.get_var(str, varname)    -- extract variable from (query) string
834    mg.get_cookie(str, cookie)  -- extract cookie from a string
835    mg.get_mime_type(filename)  -- get MIME type of a file
836    mg.get_info(infotype)       -- get server status information
837    mg.send_file(filename)      -- send a file, including all required HTTP headers
838    mg.send_file_body(filename) -- send a file, excluding HTTP headers
839    mg.url_encode(str)          -- URL encode a string
840    mg.url_decode(str, [form])  -- URL decode a string. If form=true, replace + by space.
841    mg.base64_encode(str)       -- BASE64 encode a string
842    mg.base64_decode(str)       -- BASE64 decode a string
843    mg.md5(str)                 -- return the MD5 hash of a string
844    mg.keep_alive(bool)         -- allow/forbid to use http keep-alive for this request
845    mg.request_info             -- a table with the following request information
846         .remote_addr           -- IP address of the client as string
847         .remote_port           -- remote port number
848         .server_port           -- server port number
849         .request_method        -- HTTP method (e.g.: GET, POST)
850         .http_version          -- HTTP protocol version (e.g.: 1.1)
851         .uri                   -- resource name
852         .query_string          -- query string if present, nil otherwise
853         .script_name           -- name of the Lua script
854         .https                 -- true if accessed by https://, false otherwise
855         .remote_user           -- user name if authenticated, nil otherwise
856
857connect (function):
858
859    -- Connect to the remote TCP server. This function is an implementation
860    -- of simple socket interface. It returns a socket object with three
861    -- methods: send, recv, close, which are synchronous (blocking).
862    -- connect() throws an exception on connection error.
863    -- use_ssl is not implemented.
864    connect(host, port, use_ssl)
865
866    -- Example of using connect() interface:
867    local host = 'www.example.com'  -- IP address or domain name
868    local ok, sock = pcall(connect, host, 80, 0)
869    if ok then
870      sock:send('GET / HTTP/1.0\r\n' ..
871                'Host: ' .. host .. '\r\n\r\n')
872      local reply = sock:recv()
873      sock:close()
874      -- reply now contains the web page http://www.example.com/
875    end
876
877
878All filename arguments are either absolute or relative to the CivetWeb working
879directory (not the document root or the Lua script/page file).
880
881To serve a Lua Page, CivetWeb creates a Lua context. That context is used for
882all Lua blocks within the page. That means, all Lua blocks on the same page
883share the same context. If one block defines a variable, for example, that
884variable is visible in all blocks that follow.
885
886
887**Important note on HTTP headers:**
888
889Lua scripts MUST send HTTP headers themselves, e.g.:
890
891    mg.write('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n')
892
893Lua Server Pages CAN send HTTP reply headers, like this:
894
895    HTTP/1.0 200 OK
896    Content-Type: text/html
897
898    <html><body>
899      ... the rest of the web page ...
900
901or using Lua code:
902
903    <? mg.write('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n') ?>
904    <html><body>
905      ... the rest of the web page ...
906
907or Lua Server Pages generating HTML content MAY skip the HTTP header lines.
908In this case, CivetWeb automatically creates a "200 OK"/"Content-Type: text/html"
909reply header. In this case, the document should start with "<!DOCTYPE html>"
910or "<html".
911
912Currently the extended "Kepler Syntax" is available only for text/html pages
913not sending their own HTTP headers. Thus, "Kepler Syntax" can only be used for
914HTML pages, while traditional CivetWeb syntax can be used to send a content-type
915header and generate any kind of file.
916
917
918## Websockets for Lua
919CivetWeb offers support for websockets in Lua as well. In contrast to plain
920Lua scripts and Lua server pages, Lua websocket scripts are shared by all clients.
921
922Lua websocket scripts must define a few functions:
923    open(arg)    -- callback to accept or reject a connection
924    ready(arg)   -- called after a connection has been established
925    data(arg)    -- called when the server receives data from the client
926    close(arg)   -- called when a websocket connection is closed
927All function are called with one argument of type table with at least one field
928"client" to identify the client. When "open" is called, the argument table additionally
929contains the "request_info" table as defined above. For the "data" handler, an
930additional field "data" is available. The functions "open", "ready" and "data"
931must return true in order to keep the connection open.
932
933Lua websocket pages do support single shot (timeout) and interval timers.
934
935An example is shown in
936[websocket.lua](https://github.com/civetweb/civetweb/blob/master/test/websocket.lua).
937
938
939# Using CGI
940
941Unlike some other web servers, CivetWeb does not require CGI scripts to be located
942in a special directory. CGI scripts files are recognized by the file name pattern
943and can be anywhere.
944
945When using CGI, make sure your CGI file names match the `cgi\_pattern` parameter
946configured for the server.
947Furthermore, you must either configure a `cgi\_interpreter` to be used for all
948CGI scripts, or all scripts must start with `#!` followed by the CGI
949interpreter executable, e.g.: `#!/path/to/perl.exe` or `#!/bin/sh`.
950
951See `cgi\_pattern` and `cgi\_interpreter` for more details.
952
953It is possible to disable CGI completely by building the server with
954the `NO\_CGI` define. Setting this define is required for operating
955systems not supporting `fork/exec` or `CreateProcess` (since CGI is
956based on creating child processes, it will not be available on such
957operating systems for principle reasons).
958
959Every CGI request will spawn a new child process. Data sent from the
960HTTP client to the server is passed to stdin of the child process,
961while data written to stdout by the child process is sent back to the
962HTTP client.
963
964In case a CGI script cannot handle a particular request, it might
965write a short error message to stderr instead of writing to stdout.
966This error message is added to the server error log.
967
968A script should not write to stderr after writing a reply header
969to stdout. In case CGI libraries are writing to stderr (e.g., for
970logging/debugging), the CGI script should redirect stderr to a
971user defined log file at the beginning of the script.
972
973
974FAQ
975----
976
977# Common Problems
978- PHP doesn't work - getting empty page, or 'File not found' error. The
979  reason for that is wrong paths to the interpreter. Remember that with PHP,
980  the correct interpreter is `php-cgi.exe` (`php-cgi` on UNIX).
981  Solution: specify the full path to the PHP interpreter, e.g.:
982    `CivetWeb -cgi_interpreter /full/path/to/php-cgi`
983
984- `php-cgi` is unavailable, for example on Mac OS X. As long as the `php` binary is installed, you can run CGI programs in command line mode (see the example below). Note that in this mode, `$_GET` and friends will be unavailable, and you'll have to parse the query string manually using [parse_str](http://php.net/manual/en/function.parse-str.php) and the `QUERY_STRING` environmental variable.
985
986        #!/usr/bin/php
987        <?php
988        echo "Content-Type: text/html\r\n\r\n";
989        echo "Hello World!\n";
990        ?>
991
992- CivetWeb fails to start. If CivetWeb exits immediately when started, this
993  usually indicates a syntax error in the configuration file
994  (named `civetweb.conf` by default) or the command-line arguments.
995  Syntax checking is omitted from CivetWeb to keep its size low. However,
996  the Manual should be of help. Note: the syntax changes from time to time,
997  so updating the config file might be necessary after executable update.
998  Try to use the *error\_log\_file* option for details.
999
1000- Embedding with OpenSSL on Windows might fail because of calling convention.
1001  To force CivetWeb to use `__stdcall` convention, add `/Gz` compilation
1002  flag in Visual Studio compiler.
1003