4.5. CouchDB HTTP Server

4.5.1. HTTP Server Options

[chttpd]

Note

In CouchDB 2.x, the chttpd section refers to the standard, clusteredport. All use of CouchDB, aside from a few specific maintenance tasks asdescribed in this documentation, should be performed over this port.

Defines the IP address by which the clustered port is available:

  1. [chttpd]
    bindaddress = 127.0.0.1


To let CouchDB listen any available IP address, use _0.0.0.0
:

  1. [chttpd]
    bindaddress = 0.0.0.0


For IPv6 support you need to set
::1 if you want to let CouchDBlisten correctly:

  1. [chttpd]
    bind_address = ::1


or
::_ for any available:

  1. [chttpd]
    bind_address = ::


port

Defines the port number to listen:




  1. [chttpd]
    port = 5984




To let CouchDB use any free port, set this option to 0:




  1. [chttpd]
    port = 0



preferminimal

If a request has the header
“Prefer”: “return=minimal”, CouchDBwill only send the headers that are listed for the _prefer_minimal_configuration.:




  1. [chttpd]
    prefer_minimal = Cache-Control, Content-Length, Content-Range, Content-Type, ETag, Server, Transfer-Encoding, Vary





Warning

Removing the Server header from the settings will mean thatthe CouchDB server header is replaced with theMochiWeb server header.

authentication_handlers

List of authentication handlers used by CouchDB. You mayextend them via third-party plugins or remove some of them if you won’tlet users to use one of provided methods:




  1. [chttpd]
    authentication_handlers = {chttpd_auth, cookie_authentication_handler}, {chttpd_auth, default_authentication_handler}




- {chttpd_auth, cookie_authentication_handler}: used for Cookie auth;
- {couch_httpd_auth, proxy_authentication_handler}: used for Proxy auth;
- {chttpd_auth, default_authentication_handler}: used for Basic auth;
- {couch_httpd_auth, null_authentication_handler}: disables auth.Everlasting _Admin Party
!

[httpd]

Warning

In CouchDB 2.x, the httpd section mostly refers to the node-local port,on port 5986 by default. This port is used only for maintenance andadministrative tasks. It should not be used for regular CouchDB access,and for security reasons, should always be bound to localhost(127.0.0.1) or a private LAN segment only.

allowjsonp

The true value of this option enables JSONP support (it’sfalse by default):




  1. [httpd]
    allow_jsonp = false



bind_address

Defines the IP address by which the node-local port is available.The recommended setting is always:




  1. [httpd]
    bind_address = 127.0.0.1




For IPv6 support you need to set
::1 if you want to let CouchDBlisten correctly:




  1. [httpd]
    bind_address = ::1



changes_timeout

Specifies default _timeout
value for Changes Feed inmilliseconds (60000 by default):




  1. [httpd]
    changestimeout = 60000 ; 60 seconds



config_whitelist

Sets the configuration modification whitelist. Only whitelisted valuesmay be changed via the config API. To allow theadmin to change this value over HTTP, remember to include{httpd,config_whitelist} itself. Excluding it from the list wouldrequire editing this file to update the whitelist:




  1. [httpd]
    config_whitelist = [{httpd,config_whitelist}, {log,level}, {etc,etc}]



default_handler

Specifies default HTTP requests handler:




  1. [httpd]
    default_handler = {couch_httpd_db, handle_request}



enable_cors


New in version 1.3.


Controls CORS feature:




  1. [httpd]
    enable_cors = false



port

Defines the port number to listen:




  1. [httpd]
    port = 5986




To let CouchDB use any free port, set this option to 0:




  1. [httpd]
    port = 0



redirect_vhost_handler

This option customizes the default function that handles requests tovirtual hosts:




  1. [httpd]
    redirect_vhost_handler = {Module, Fun}




The specified function take 2 arguments: the MochiWeb request objectand the target path.
server_options

Server options for the MochiWeb component of CouchDB can be added tothe configuration files:




  1. [httpd]
    server_options = [{backlog, 128}, {acceptor_pool_size, 16}]



secure_rewrites

This option allow to isolate databases via subdomains:




  1. [httpd]
    secure_rewrites = true



socket_options

The socket options for the listening socket in CouchDB, as set at thebeginning of ever request, can be specified as a list of tuples. For example:




  1. [httpd]
    socket_options = [{sndbuf, 262144}, {nodelay, true}]




The options supported are a subset of full options supported by theTCP/IP stack. A list of the supported options are provided in theErlang inet documentation.
server_options

The server options for any socket in the mochiweb acceptor pool in CouchDBcan be specified as a list of tuples. For example:




  1. [httpd]
    server_options = [{recbuf, undefined}]




The options supported are a subset of full options supported by theTCP/IP stack. A list of the supported options are provided in theErlang inet documentation.
vhost_global_handlers

List of global handlers that are available for virtual hosts:




  1. [httpd]
    vhost_global_handlers = _utils, _uuids, _session, _users



x_forwarded_host

The _x_forwarded_host
header (X-Forwarded-Host by default) is usedto forward the original value of the Host header field in case, forexample, if a reverse proxy is rewriting the “Host” header field tosome internal host name before forward the request to CouchDB:




  1. [httpd]
    xforwarded_host = X-Forwarded-Host




This header has higher priority above Host one, if only it existsin the request.
x_forwarded_proto

_x_forwarded_proto
header (X-Forwarder-Proto by default) is usedfor identifying the originating protocol of an HTTP request, since areverse proxy may communicate with CouchDB instance using HTTP even ifthe request to the reverse proxy is HTTPS:




  1. [httpd]
    xforwarded_proto = X-Forwarded-Proto



x_forwarded_ssl

The _x_forwarded_ssl
header (X-Forwarded-Ssl by default) tellsCouchDB that it should use the https scheme instead of the http.Actually, it’s a synonym for X-Forwarded-Proto: https header, butused by some reverse proxies:




  1. [httpd]
    xforwarded_ssl = X-Forwarded-Ssl



enable_xframe_options

Controls Enables or disabled feature:




  1. [httpd]
    enable_xframe_options = false



WWW-Authenticate

Set this option to trigger basic-auth pop-up on unauthorized requests:




  1. [httpd]
    WWW-Authenticate = Basic realm="Welcome to the Couch!"



max_http_request_size


Changed in version 2.1.0.


Limit the maximum size of the HTTP request body. This setting appliesto all requests and it doesn’t discriminate between single vs.multi-document operations. So setting it to 1MB would block a_PUT
of a document larger than 1MB, but it might also block a_bulk_docs update of 1000 1KB documents, or a multipart/relatedupdate of a small document followed by two 512KB attachments. Thissetting is intended to be used as a protection against maliciouslylarge HTTP requests rather than for limiting maximum document sizes.




  1. [httpd]
    max_http_request_size = 4294967296 ; 4 GB





Warning

Before version 2.1.0 couchdb/max_document_size wasimplemented effectively as max_http_request_size. That is, itchecked HTTP request bodies instead of document sizes. After theupgrade, it is advisable to review the usage of these configurationsettings.

4.5.2. HTTPS (SSL/TLS) Options

[ssl]

CouchDB supports TLS/SSL natively, without the use of a proxy server.

HTTPS setup can be tricky, but the configuration in CouchDB was designed tobe as easy as possible. All you need is two files; a certificate and aprivate key. If you have an official certificate from a certificateauthority, both should be in your possession already.

If you just want to try this out and don’t want to go through the hassle ofobtaining an official certificate, you can create a self-signed certificate.Everything will work the same, but clients will get a warning about an insecurecertificate.

You will need the OpenSSL command line tool installed. It probablyalready is.




  1. shell> mkdir /etc/couchdb/cert
    shell> cd /etc/couchdb/cert
    shell> openssl genrsa > privkey.pem
    shell> openssl req -new -x509 -key privkey.pem -out couchdb.pem -days 1095
    shell> chmod 600 privkey.pem couchdb.pem
    shell> chown couchdb privkey.pem couchdb.pem




Now, you need to edit CouchDB’s configuration, by editing yourlocal.ini file. Here is what you need to do.

Under the [ssl] section, enable HTTPS and set up the newly generatedcertificates:




  1. [ssl]
    enable = true
    certfile = /etc/couchdb/cert/couchdb.pem
    key_file = /etc/couchdb/cert/privkey.pem




For more information please read certificates HOWTO.

Now start (or restart) CouchDB. You should be able to connect to itusing HTTPS on port 6984:




  1. shell> curl https://127.0.0.1:6984/
    curl: (60) SSL certificate problem, verify that the CA cert is OK. Details:
    error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
    More details here: http://curl.haxx.se/docs/sslcerts.html

    curl performs SSL certificate verification by default, using a "bundle"
    of Certificate Authority (CA) public keys (CA certs). If the default
    bundle file isn't adequate, you can specify an alternate file
    using the —cacert option.
    If this HTTPS server uses a certificate signed by a CA represented in
    the bundle, the certificate verification probably failed due to a
    problem with the certificate (it might be expired, or the name might
    not match the domain name in the URL).
    If you'd like to turn off curl's verification of the certificate, use
    the -k (or —insecure) option.




Oh no! What happened?! Remember, clients will notify their users that yourcertificate is self signed. curl is the client in this case and itnotifies you. Luckily you trust yourself (don’t you?) and you can specifythe -k option as the message reads:




  1. shell> curl -k https://127.0.0.1:6984/
    {"couchdb":"Welcome","version":"1.5.0"}




All done.

For performance reasons, and for ease of setup, you may still wish toterminate HTTPS connections at your load balancer / reverse proxy, then useunencrypted HTTP between it and your CouchDB cluster. This is a recommendedapproach.
cacert_file

The path to a file containing PEM encoded CA certificates. The CAcertificates are used to build the server certificate chain, and forclient authentication. Also the CAs are used in the list of acceptableclient CAs passed to the client when a certificate is requested. May beomitted if there is no need to verify the client and if there are notany intermediate CAs for the server certificate:




  1. [ssl]
    cacert_file = /etc/ssl/certs/ca-certificates.crt



cert_file

Path to a file containing the user’s certificate:




  1. [ssl]
    cert_file = /etc/couchdb/cert/couchdb.pem



key_file

Path to file containing user’s private PEM encoded key:




  1. [ssl]
    key_file = /etc/couchdb/cert/privkey.pem



password

String containing the user’s password. Only used if the private key fileis password protected:




  1. [ssl]
    password = somepassword



ssl_certificate_max_depth

Maximum peer certificate depth (must be set even if certificatevalidation is off):




  1. [ssl]
    ssl_certificate_max_depth = 1



verify_fun

The verification fun (optional) if not specified, the defaultverification fun will be used:




  1. [ssl]
    verify_fun = {Module, VerifyFun}



verify_ssl_certificates

Set to _true
to validate peer certificates:




  1. [ssl]
    verifyssl_certificates = false



fail_if_no_peer_cert

Set to _true
to terminate the TLS/SSL handshake with ahandshake_failure alert message if the client does not send acertificate. Only used if verify_ssl_certificates is true. If setto false it will only fail if the client sends an invalid certificate(an empty certificate is considered valid):




  1. [ssl]
    failif_no_peer_cert = false



secure_renegotiate

Set to _true
to reject renegotiation attempt that does not live up toRFC 5746:




  1. [ssl]
    secure_renegotiate = true



ciphers

Set to the cipher suites that should be supported which can bespecified in erlang format “{ecdhe_ecdsa,aes_128_cbc,sha256}” orin OpenSSL format “ECDHE-ECDSA-AES128-SHA256”.




  1. [ssl]
    ciphers = ["ECDHE-ECDSA-AES128-SHA256", "ECDHE-ECDSA-AES128-SHA"]



tls_versions

Set to a list of permitted SSL/TLS protocol versions:




  1. [ssl]
    tls_versions = [tlsv1 | 'tlsv1.1' | 'tlsv1.2']



4.5.3. Cross-Origin Resource Sharing

[cors]


New in version 1.3: added CORS support, see JIRA COUCHDB-431


CORS, or “Cross-Origin Resource Sharing”, allows a resource such as a webpage running JavaScript inside a browser, to make AJAX requests(XMLHttpRequests) to a different domain, without compromising the securityof either party.

A typical use case is to have a static website hosted on a CDN makerequests to another resource, such as a hosted CouchDB instance. Thisavoids needing an intermediary proxy, using JSONP or similar workaroundsto retrieve and host content.

While CouchDB’s integrated HTTP server has support for document attachmentsmakes this less of a constraint for pure CouchDB projects, there are manycases where separating the static content from the database access isdesirable, and CORS makes this very straightforward.

By supporting CORS functionality, a CouchDB instance can accept directconnections to protected databases and instances, without the browserfunctionality being blocked due to same-origin constraints. CORS issupported today on over 90% of recent browsers.

CORS support is provided as experimental functionality in 1.3, and as suchwill need to be enabled specifically in CouchDB’s configuration. While allorigins are forbidden from making requests by default, support is availablefor simple requests, preflight requests and per-vhost configuration.

This section requires httpd/enable_cors option havetrue value:




  1. [httpd]
    enable_cors = true



credentials

By default, neither authentication headers nor cookies are included inrequests and responses. To do so requires both settingXmlHttpRequest.withCredentials = true on the request object in thebrowser and enabling credentials support in CouchDB.




  1. [cors]
    credentials = true




CouchDB will respond to a credentials-enabled CORS request with anadditional header, Access-Control-Allow-Credentials=true.
origins

List of origins separated by a comma, means accept all. You can’tset origins = and credentials = true option at the sametime:




  1. [cors]
    origins = *




Access can be restricted by protocol, host and optionally by port.Origins must follow the scheme: http://example.com:80:




  1. [cors]
    origins = http://localhost, https://localhost, http://couch.mydev.name:8080




Note that by default, no origins are accepted. You must define themexplicitly.
headers

List of accepted headers separated by a comma:




  1. [cors]
    headers = X-Couch-Id, X-Couch-Rev



methods

List of accepted methods:




  1. [cors]
    methods = GET,POST



See also

Original JIRA implementation ticket

Standards and References:

4.5.3.1. Per Virtual Host Configuration

To set the options for a vhosts, you will need to create a sectionwith the vhost name prefixed by cors:. Example case for the vhostexample.com:

  1. [cors:example.com]
  2. credentials = false
  3. ; List of origins separated by a comma
  4. origins = *
  5. ; List of accepted headers separated by a comma
  6. headers = X-CouchDB-Header
  7. ; List of accepted methods
  8. methods = HEAD, GET

4.5.4. Virtual Hosts

[vhosts]

CouchDB can map requests to different locations based on the Hostheader, even if they arrive on the same inbound IP address.

This allows different virtual hosts on the same machine to map to differentdatabases or design documents, etc. The most common use case is to map avirtual host to a Rewrite Handler, to providefull control over the application’s URIs.

To add a virtual host, add a CNAME pointer to the DNS for your domainname. For development and testing, it is sufficient to add an entry in thehosts file, typically /etc/hosts` on Unix-like operating systems:




  1. # CouchDB vhost definitions, refer to local.ini for further details
    127.0.0.1 couchdb.local




Test that this is working:




  1. $ ping -n 2 couchdb.local
    PING couchdb.local (127.0.0.1) 56(84) bytes of data.
    64 bytes from localhost (127.0.0.1): icmpreq=1 ttl=64 time=0.025 ms
    64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.051 ms




Finally, add an entry to your configuration file in the[vhosts] section:




  1. [vhosts]
    couchdb.local:5984 = /example
    *.couchdb.local:5984 = /example




If your CouchDB is listening on the the default HTTP port (80), or issitting behind a proxy, then you don’t need to specify a port number in the_vhost
key.

The first line will rewrite the request to display the content of theexample database. This rule works only if the Host header iscouchdb.local and won’t work for CNAMEs. The second rule, on theother hand, matches all CNAMEs to example db, so that bothwww.couchdb.local and db.couchdb.local will work.

4.5.4.1. Rewriting Hosts to a Path

Like in the _rewrite handler you can match somevariable and use them to create the target path. Some examples:

  1. [vhosts]
  2. *.couchdb.local = /*
  3. :dbname. = /:dbname
  4. :ddocname.:dbname.example.com = /:dbname/_design/:ddocname/_rewrite

The first rule passes the wildcard as dbname. The second one does the same,but uses a variable name. And the third one allows you to use any URL withddocname in any database with dbname.

You could also change the default function to handle request by changing thesetting httpd/redirect_vhost_handler.

4.5.5. X-Frame-Options

X-Frame-Options is a response header that controls whether a http responsecan be embedded in a <frame>, <iframe> or <object>. This is a securityfeature to help against clickjacking.

[x_frame_options]; Settings same-origin will return X-Frame-Options: SAMEORIGIN.; If same origin is set, it will ignore the hosts setting; same_origin = true; Settings hosts will; return X-Frame-Options: ALLOW-FROM https://example.com/; List of hosts separated by a comma. * means accept all; hosts =

If xframeoptions is enabled it will return _X-Frame-Options: DENY by default.If same_origin is enabled it will return X-Frame-Options: SAMEORIGIN.A X-FRAME-OPTIONS: ALLOW-FROM url will be returned when same_origin_is false, and the HOST header matches one of the urls in the _hosts config.Otherwise a X-Frame-Options: DENY will be returned.

原文: http://docs.couchdb.org/en/stable/config/http.html