Skip to content

Instantly share code, notes, and snippets.

@MrYoda
Created March 15, 2017 09:39
Show Gist options
  • Save MrYoda/06c9d01c4223244a5091a11e7290ac1f to your computer and use it in GitHub Desktop.
Save MrYoda/06c9d01c4223244a5091a11e7290ac1f to your computer and use it in GitHub Desktop.
Nginx CouchDB proxy without authentication for safe HTTP methods only, with named location and images 404 fallback
# HTTP server: Enforce HTTPS by HTTP 301
server {
listen 80;
listen [::]:80 ipv6only=on;
server_name couch-gateway.site.ru;
return 301 https://$server_name$request_uri;
}
# SSL server
server {
listen 443 ssl http2;
listen [::]:443 ipv6only=on ssl http2;
server_name couch-gateway.site.ru;
ssl_certificate /etc/letsencrypt/live/couch-gateway.site.ru/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/couch-gateway.site.ru/privkey.pem;
include snippets/ssl-params.conf;
include snippets/ssl-hsts.conf;
access_log /var/log/nginx/couch-gateway.site.ru.access.log;
error_log /var/log/nginx/couch-gateway.site.ru.error.log;
root /var/www/html;
add_header Allow "GET, OPTIONS, HEAD" always;
location = /favicon.ico {
access_log off;
log_not_found off;
}
# All requests except sized images
location / {
try_files $uri @couch_proxy;
}
# Sized images requests
location ~* ([0-9]+)x([0-9]+)([_0-9a-zA-Z]*)\.(jpg|jpeg|gif|png)$ {
set $X $1;
set $Y $2;
set $LABEL $3;
set $EXT $4;
try_files $uri @couch_proxy;
}
# Couch proxy for all requests
location @couch_proxy{
if ( $request_method !~ ^(GET|OPTIONS|HEAD)$ ) {
return 405;
}
proxy_pass http://localhost:5984;
proxy_set_header Authorization "Basic BASE64OFADMINPASSWORD=="; # base64 of "admin:adminpassword"
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_intercept_errors on;
error_page 404 /images/unavailable/${X}x${Y}.jpg;
}
# LetsEncrypt acme challenge
location ~ /.well-known {
root /var/www/html;
}
}
@MrYoda
Copy link
Author

MrYoda commented Mar 15, 2017

  • proxies all safe (GET, OPTIONS, HEAD) requests to couchdb transparently, in case of other HTTP methods - returns 405; via named location @couch_proxy
  • for images:
    • supports names by mask: WxH[_LABEL].EXT, W - width, H - height, EXT - file extension, LABEL - any text after WxH and before EXT
    • trying to serve request via @couch_proxy, if 404 (image attachment not found) - returns image stub /images/unavailable/${X}x${Y}.jpg;
  • HTTPS with Lets Encrypt certificates and enforcement (HTTP 301 redirect from http:// and HSTS headers).

TODO: nginx cache of successful image responses

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment