├── .github └── workflows │ └── docker-build.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── acl ├── allow-internal └── deny-all ├── content ├── README └── default │ └── healthcheck │ └── index.html ├── global.d ├── access.conf ├── default-server.conf ├── fastcgi.conf ├── geoip.conf ├── gzip.conf ├── headers.conf ├── limit.conf ├── log.conf ├── map.conf ├── mime-types.conf ├── proxy.conf ├── real-ip.conf ├── ssl-dhparam.pem ├── ssl.conf ├── upstream.conf └── userid.conf ├── include ├── akamai-client-ip ├── allow-cors ├── allow-websockets ├── assets-base ├── cache-locally ├── cache-logged-out ├── cloudflare-client-ip ├── cookies-only ├── deny-abusive ├── deny-iframing ├── down-for-maintenance ├── fastcgi-params ├── forceerror-cookie ├── get-only ├── insecure-only ├── no-args ├── no-cache ├── no-store ├── pretty-error-pages ├── proxy-headers ├── proxy-headers-external ├── proxy-headers-minimal ├── proxy-to-s3 ├── redirect-to-secure ├── response-headers ├── retry-404s ├── secure-only ├── server-base └── static-assets ├── listen ├── example.com ├── example.org ├── misc └── redirector ├── nginx.conf ├── root ├── README ├── example.com │ ├── apple-touch-icon.png │ ├── favicon.ico │ └── proxyerror │ │ ├── 403.html │ │ ├── 404.html │ │ ├── 413.html │ │ ├── 418.html │ │ ├── 429.html │ │ ├── 50x.html │ │ ├── 520.html │ │ ├── blank.html │ │ └── nocache.html ├── example.org │ ├── apple-touch-icon.png │ ├── favicon.ico │ └── proxyerror │ │ ├── 403.html │ │ ├── 404.html │ │ ├── 413.html │ │ ├── 418.html │ │ ├── 429.html │ │ ├── 50x.html │ │ ├── 520.html │ │ ├── blank.html │ │ └── nocache.html └── shared │ ├── crossdomain.xml │ ├── robots-example.com.txt │ ├── robots-www.example.com.txt │ ├── robots-www.example.org.txt │ └── robots.txt └── sites.d ├── admin.example.com.conf ├── wildcard.example.com.conf ├── wildcard.example.org.conf ├── www.example.com.conf └── www.example.org.conf /.github/workflows/docker-build.yml: -------------------------------------------------------------------------------- 1 | name: docker-build 2 | on: 3 | push: 4 | pull_request: 5 | schedule: 6 | - cron: '22 4 20 * *' 7 | 8 | jobs: 9 | 10 | test: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | fail-fast: false 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - run: docker build -f Dockerfile . 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # A Dockerfile which gets a minimal nginx test environment set up, allowing 2 | # Github Actions to ask nginx if this config is valid. 3 | 4 | FROM ubuntu:18.04 5 | 6 | RUN apt-get -q update && \ 7 | apt-get -y -q dist-upgrade && \ 8 | DEBIAN_FRONTEND=noninteractive apt-get install -y -q --no-install-recommends ca-certificates curl geoip-database-extra gnupg2 openssl && \ 9 | ln -s GeoIPCity.dat /usr/share/GeoIP/GeoLiteCity.dat && \ 10 | mkdir /etc/ssl-example && \ 11 | printf "\n\n\n\n\nwww.example.com\n\n" | openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout /etc/ssl-example/wildcard.example.com.key -out /etc/ssl-example/wildcard.example.com.crt && \ 12 | printf "\n\n\n\n\nwww.example.org\n\n" | openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout /etc/ssl-example/wildcard.example.org.key -out /etc/ssl-example/wildcard.example.org.crt && \ 13 | echo "deb http://nginx.org/packages/ubuntu/ bionic nginx" >> /etc/apt/sources.list && \ 14 | curl -sSL https://nginx.org/keys/nginx_signing.key | apt-key add - && \ 15 | apt-get -q update && \ 16 | DEBIAN_FRONTEND=noninteractive apt-get install -y -q --no-install-recommends nginx nginx-module-geoip 17 | 18 | ADD . /etc/nginx-test 19 | 20 | RUN nginx -c /etc/nginx-test/nginx.conf -t 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nginx-config-example [![Build Status](https://github.com/die-net/nginx-config-example/actions/workflows/docker-build.yml/badge.svg)](https://github.com/die-net/nginx-config-example/actions/workflows/docker-build.yml) 2 | 3 | This is a complex [NginX](http://nginx.org/en/) configuration example that incorporates much of what I have learned about running NginX for years at scale at several large sites I've been involved with. 4 | 5 | The most interesting features are: 6 | 7 | * A rich set of [includes](https://github.com/die-net/nginx-config-example/tree/main/include) to add functionality at the server block or location block level. 8 | * The use of [maps](https://github.com/die-net/nginx-config-example/blob/main/global.d/map.conf) to do complex conditionals instead of trying to rely on the limited "if". 9 | * The use of chained "geo" and "map" to do [conditional rate-limiting](https://github.com/die-net/nginx-config-example/blob/main/global.d/limit.conf). 10 | 11 | There are other goodies sprinkled throughout. 12 | 13 | It is meant to be used as the basis for your own NginX config. Copy and modify it, removing the parts that aren't relevant to you. 14 | -------------------------------------------------------------------------------- /acl/allow-internal: -------------------------------------------------------------------------------- 1 | # Internal IPs 2 | 3 | # Private networks 4 | allow 10.0.0.0/8; 5 | allow 172.16.0.0/12; 6 | allow 192.168.0.0/16; 7 | 8 | # Our own servers 9 | #allow 198.51.100.0/24; 10 | #allow 2001:db0:0::/48; 11 | -------------------------------------------------------------------------------- /acl/deny-all: -------------------------------------------------------------------------------- 1 | # Use at the end of a list of "allow" statements or includes, to deny all 2 | # other IPs. 3 | 4 | deny all; 5 | 6 | # In this safe, ACLed location block, replace the default limit_req. Trust 7 | # our partners with a very high rate-limit, allowing up to 100 requests per 8 | # second per IP, and delay up to 10 seconds to be able to fulfill that 9 | # without throwing a 503. 10 | 11 | limit_req zone=fast_limit_buckets burst=5000; 12 | -------------------------------------------------------------------------------- /content/README: -------------------------------------------------------------------------------- 1 | Complete sites served by NginX, except for paths that are served from 2 | /etc/nginx/root/ such as /favicon.ico, /proxyerror/, /robots.txt, etc. 3 | 4 | The "default" site is served when nothing else matches, such as when 5 | receiving requests without a Host header or that mention our server IPs. 6 | We make requests from ELBs to /healthcheck/ that relies on this. 7 | -------------------------------------------------------------------------------- /content/default/healthcheck/index.html: -------------------------------------------------------------------------------- 1 | iamalive 2 | -------------------------------------------------------------------------------- /global.d/access.conf: -------------------------------------------------------------------------------- 1 | # Access Module: http://wiki.nginx.org/HttpAccessModule 2 | 3 | # Catch configuration mistakes by disallowing connecting to ourselves. 4 | deny 127.0.0.0/8; # Localhost 5 | 6 | # Allow the rest of the world. 7 | allow all; 8 | -------------------------------------------------------------------------------- /global.d/default-server.conf: -------------------------------------------------------------------------------- 1 | # Each ORIGIN_IP_* should have a corresponding entry in here. Because they 2 | # are seen first in the config, these are the default servers for a request 3 | # on a given IP when no other server_names match. The server_names here 4 | # should be unique strings that will never match a real hostname, but are 5 | # otherwise ignored. 6 | 7 | 8 | # The default directory root for static content, if not overridden. 9 | root /etc/nginx/root/example.com; 10 | 11 | 12 | # The default SSL cert. 13 | ssl_certificate /etc/ssl-example/wildcard.example.com.crt; 14 | ssl_certificate_key /etc/ssl-example/wildcard.example.com.key; 15 | 16 | 17 | # The default server for any IPs not listed later. Must be listed first. 18 | # 19 | # The combination of "bind" and "backlog" sets the SYN_RECV queue limit for 20 | # all IPs. The best-practice "backlog" value is roughly be equivalent to 21 | # the peak number of new ESTABLISHED connections per second we expect. The 22 | # Linux sysctl net.ipv4.tcp_max_syn_backlog needs to be at least this. 23 | # 24 | # "so_keepalive=45:45:4" means send a TCP keepalive packet every 45 seconds, 25 | # to prevent bad firewalls from stalling long-lived persistent connections. 26 | # 27 | # "reuseport" is available as of Linux 3.9 and improves accept() scalability. 28 | 29 | server { 30 | listen 80 default_server reuseport backlog=10000 so_keepalive=45:45:4 bind; 31 | listen [::]:80 default_server reuseport backlog=10000 so_keepalive=45:45:4 bind; 32 | listen 443 default_server reuseport backlog=10000 so_keepalive=45:45:4 bind ssl http2; 33 | listen [::]:443 default_server reuseport backlog=10000 so_keepalive=45:45:4 bind ssl http2; 34 | 35 | server_name _; 36 | 37 | include include/server-base; 38 | 39 | # Not necessary. We do this to just to get the variables set somewhere. 40 | include include/deny-iframing; 41 | include include/allow-cors; 42 | include include/allow-websockets; 43 | 44 | location / { 45 | include include/get-only; 46 | return 404; 47 | } 48 | 49 | location /healthcheck/ { 50 | root /etc/nginx/content/default; 51 | allow all; 52 | access_log off; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /global.d/fastcgi.conf: -------------------------------------------------------------------------------- 1 | # FastCGI Module: http://wiki.nginx.org/HttpFastcgiModule 2 | 3 | include include/fastcgi-params; 4 | 5 | fastcgi_intercept_errors on; 6 | fastcgi_keep_conn on; 7 | fastcgi_index index.php; 8 | 9 | # Set up some limits on proxy timeouts and sizes. 10 | fastcgi_connect_timeout 2s; 11 | fastcgi_read_timeout 20s; 12 | fastcgi_send_timeout 10s; 13 | fastcgi_buffers 64 4k; 14 | fastcgi_max_temp_file_size 25m; 15 | fastcgi_next_upstream error timeout invalid_header http_500 http_503; 16 | -------------------------------------------------------------------------------- /global.d/geoip.conf: -------------------------------------------------------------------------------- 1 | # GeoIP Module: http://wiki.nginx.org/HttpGeoipModule 2 | 3 | # ~50 meg database for IP->zip lookups. 4 | #geoip_city /usr/share/GeoIP/GeoIPCity.dat; 5 | geoip_city /usr/share/GeoIP/GeoLiteCity.dat; 6 | 7 | 8 | # Generate $x_geo (X-Geo header) based on $remote_addr and $geoip_*. 9 | # The first regexp that matches here wins. 10 | 11 | map "$remote_addr;country=$geoip_city_country_code;region=$geoip_region;zip=$geoip_postal_code;lat=$geoip_latitude;long=$geoip_longitude" $x_geo { 12 | "~^[0-9.]+;(?Pcountry=[A-Z][A-Z];.*)$" $geo; 13 | "~^10\." "country=US;region=CA;zip=90066;lat=34.015;long=-118.434"; 14 | "~^[0-9.]+;(?Pcountry=[A-Z][0-9]);" $geo; 15 | default ""; 16 | } 17 | 18 | # Generate $x_zip (used by some /etc/nginx/content/ SSI) based on 19 | # $remote_addr and $geoip_*. The first regexp that matches here wins. 20 | 21 | map "$remote_addr;$geoip_city_country_code;$geoip_postal_code" $x_zip { 22 | "~^[\d.]+;US;(?P\d{5})$" $zip; 23 | "~^10\." 90066; 24 | default ""; 25 | } 26 | -------------------------------------------------------------------------------- /global.d/gzip.conf: -------------------------------------------------------------------------------- 1 | # Gzip Module: http://wiki.nginx.org/HttpGzipModule 2 | 3 | # Gzip enabled by default. 4 | gzip on; 5 | 6 | # Gzip level 1 is the best ratio of bytes saved per second of CPU. 7 | gzip_comp_level 1; 8 | 9 | # Gunzip content if we have gzipped content but client can't support it. 10 | gunzip on; 11 | 12 | # For text/html plus the following list of MIME types. 13 | gzip_types 14 | text/css 15 | text/javascript 16 | text/plain 17 | text/xml 18 | application/atom+xml 19 | application/json 20 | application/vnd.ms-fontobject 21 | application/x-font-ttf 22 | application/x-javascript 23 | application/x-thrift 24 | application/xhtml+xml 25 | application/xml 26 | application/xml+rss 27 | image/svg+xml 28 | image/x-icon 29 | font/opentype 30 | font/ttf 31 | ; 32 | 33 | # Skip gzip for very short responses. 34 | gzip_min_length 600; 35 | 36 | # To make sure intermediate proxies don't try to serve cached responses to 37 | # clients who don't ask for it, we send the "Vary: Accept-Encoding" header, 38 | # which is only understood by HTTP/1.1 proxies. Don't gzip if the client is 39 | # HTTP/1.0. 40 | gzip_http_version 1.1; 41 | gzip_vary on; 42 | gzip_proxied any; 43 | 44 | # IE versions 5.5 and 6 claim to handle gzip, but don't do so properly. 45 | # Don't send them gzipped content. 46 | gzip_disable "msie6"; 47 | -------------------------------------------------------------------------------- /global.d/headers.conf: -------------------------------------------------------------------------------- 1 | # By default, we filter all request headers proxied to an app, except those 2 | # explicitly whitelisted via proxy_set_header. 3 | 4 | proxy_pass_request_headers off; 5 | 6 | # Because of NginX's unusual config block inheritence model, using any 7 | # add_header, proxy_hide_header, or proxy_set_header statements in a server 8 | # or location block replaces previous settings. This, these must be 9 | # included again when these statements are used later. 10 | 11 | include include/proxy-headers; 12 | 13 | include include/response-headers; 14 | -------------------------------------------------------------------------------- /global.d/limit.conf: -------------------------------------------------------------------------------- 1 | # Nginx's DoS protection is fast, but not very flexible. You can't really 2 | # track request rate-limits or connection counts separately per upstream 3 | # service; they are global to the proxy. The only real flexibility comes 4 | # from which connections are grouped together into a "bucket", and the 5 | # limits are global to all connections in the bucket. 6 | # 7 | # limit_req implements a "leaky bucket" model. Each bucket holds at most 8 | # tokens and starts out empty. One token added to the bucket per 9 | # request, and tokens leak out of the bucket at fixed . If the bucket 10 | # is full, the bucket is unchanged and requests are answered with 503. No 11 | # tokens leak out of the bucket when it is empty. 12 | # 13 | # A bucket key can be defined as basically any string, but you don't want to 14 | # use a string that is under control of an attacker. We limit ourselves to 15 | # IP address and MaxMind's idea of country for that IP. The goal is to make 16 | # as close as possible to one bucket available to an attacker with limited 17 | # resources, while not putting too many real users in the same bucket. We 18 | # can also exempt IPs that we trust from being limited at all. 19 | # 20 | # Limit types: 21 | # i: exempt from limits, internal IPs owned by us. 22 | # e: exempt from limits, not owned by us. 23 | # s: bucketed by individual IP. 24 | # n: bucketed by /24 network. 25 | # c: bucketed by country code. 26 | # a: abusive IPs, put in one shared bucket. 27 | # 28 | # $x_limit_type checks $x_limit_type_ip, and if it returns "", then it 29 | # checks $x_limit_type_country. $x_limit_bucket then takes the type and 30 | # returns the appropriate key identifying a unique bucket. 31 | 32 | 33 | # $x_limit_type_ip: If an IP is listed, return limit type. Otherwise, 34 | # return "" to allow pass-through to country. This is implemented using the 35 | # IP optimized "geo" map, which can handle a large number (100,000+) of 36 | # entries efficiently, but can't return variables. 37 | 38 | geo $x_limit_type_ip { 39 | ## Exempt all internal IPs: 40 | 41 | 127.0.0.0/8 i; # Localhost 42 | 43 | 192.168.0.0/16 i; # Local net 44 | 172.16.0.0/12 i; 45 | 10.0.0.0/8 i; 46 | 47 | #198.51.100.0/24; i; # Our own servers 48 | #2001:db0:0::/48; 49 | 50 | 51 | ## Exempt web crawlers that we care about: 52 | 53 | # Google's web crawler IP range: 54 | 66.249.64.0/19 e; 55 | 56 | # And bingbot: 57 | 40.77.167.0/24 e; 58 | 157.55.39.0/24 e; 59 | 207.46.13.0/24 e; 60 | 61 | # Gmail's image proxy 62 | 66.102.6.0/23 e; 63 | 66.102.8.0/23 e; 64 | 65 | 66 | ## None of the above: 67 | 68 | # If no match, must return "": 69 | default ""; 70 | } 71 | 72 | 73 | # Do MaxMind GeoIP lookup on country, see if we specify a limit type for 74 | # it, and if not return "". Only called when the IP lookup returns "". 75 | 76 | map $geoip_city_country_code $x_limit_type_country { 77 | # Anonymous proxies are MaxMind country code "A1". See 78 | # http://www.maxmind.com/app/iso3166 for full list. 79 | A1 c; 80 | 81 | # High-risk botnet countries. See: 82 | # http://www.team-cymru.org/Monitoring/Graphs/ 83 | BR c; 84 | CN c; 85 | ID c; 86 | IN c; 87 | IT c; 88 | NG c; 89 | PK c; 90 | RO c; 91 | RU c; 92 | TH c; 93 | TR c; 94 | UA c; 95 | VN c; 96 | 97 | # If no match, must return "": 98 | default ""; 99 | } 100 | 101 | 102 | # $x_limit_type: Simple if/then/else-style map. Check $x_limit_type_ip 103 | # first. If it returns "", check $x_limit_type_country. 104 | 105 | map $x_limit_type_ip $x_limit_type { 106 | "" $x_limit_type_country; 107 | default $x_limit_type_ip; 108 | } 109 | 110 | 111 | # $x_limit_bucket: Translate $x_limit_type into a very short key 112 | # identifying bucket which shares connection/request limits with all other 113 | # connections in the same bucket. The key "" is special and means "don't 114 | # limit at all". 115 | 116 | map $x_limit_type $x_limit_bucket { 117 | i ""; # i: Exempt internal IPs skip limits. 118 | e ""; # e: Exempt external IPs skip limits. 119 | s $binary_remote_addr; # s: Use the single IP address. 120 | n $binary_remote_net; # n: Use the /24 (from include/map). 121 | c $geoip_city_country_code; # c: Country code as name. 122 | a "a"; # a: Abusive IPs share one bucket ("a"). 123 | 124 | default $binary_remote_net; # No matches, default to bucketing by /24. 125 | } 126 | 127 | 128 | # By default, allow 500 requests at any speed plus 30 requests per minute 129 | # over an extended period. Exceeding that throws 429s, with no attempt to 130 | # delay. "10m" (10 megabytes) can support ~160000 buckets. 131 | 132 | limit_req_status 429; 133 | limit_req_zone $x_limit_bucket zone=limit_buckets:10m rate=30r/m; 134 | limit_req zone=limit_buckets burst=500 nodelay; 135 | 136 | 137 | # $x_write_limit_bucket: Only rate-limit if $request_method is not GET or 138 | # HEAD. 139 | 140 | map $request_method $x_write_limit_bucket { 141 | GET ""; 142 | HEAD ""; 143 | default $x_limit_bucket; 144 | } 145 | 146 | 147 | # We also seperately rate-limit non-GET/HEAD to 50 requests at any speed 148 | # plus 2 requests per minute. Exceeding that throws 429s, with no attempt 149 | # to delay. "10m" (10 megabytes) can support ~160000 buckets. 150 | 151 | limit_req_zone $x_write_limit_bucket zone=write_limit_buckets:10m rate=2r/m; 152 | limit_req zone=write_limit_buckets burst=50 nodelay; 153 | -------------------------------------------------------------------------------- /global.d/log.conf: -------------------------------------------------------------------------------- 1 | # Log Module: http://wiki.nginx.org/HttpLogModule 2 | 3 | # Don't write missing files to error.log. 4 | log_not_found off; 5 | 6 | log_format request '$msec' 7 | '\t$remote_addr' 8 | '\t$http_x_forwarded_for' 9 | '\t$geoip_city_country_code/$geoip_region/$geoip_postal_code' 10 | '\t$scheme://$host$request_uri' 11 | '\t$ssl_protocol/$ssl_cipher' 12 | '\t$server_protocol' 13 | '\t$request_method' 14 | '\t$status' 15 | '\t$upstream_status' 16 | '\t$body_bytes_sent' 17 | '\t$gzip_ratio' 18 | '\t$request_time' 19 | '\t$upstream_response_time' 20 | '\t-' # '\t$tcpinfo_rtt/$tcpinfo_rttvar/$tcpinfo_snd_cwnd' 21 | '\t$upstream_addr' 22 | '\t$upstream_cache_status/$proxy_host' 23 | '\t$cookie_u' 24 | '\t$connection/$pid/$remote_port/$connection_requests/$x_limit_type/$user_agent_class/$is_mobile/$prefer_mime_type/$prefer_language' 25 | '\t$http_referer' 26 | '\t$http_user_agent' 27 | '\t$cookie_username' 28 | '\t$upstream_http_x_log' 29 | ; 30 | 31 | access_log /var/log/nginx/request.log request; 32 | -------------------------------------------------------------------------------- /global.d/map.conf: -------------------------------------------------------------------------------- 1 | # Map Module: http://wiki.nginx.org/HttpMapModule 2 | # 3 | # Maps translate a source string to an output variable and are 4 | # lazy-evaluated, only generating the answer when the output variable is 5 | # referenced. They are preferred over set/if/set sequences. 6 | 7 | 8 | # Generate $binary_remote_net from first part of $binary_remote_addr. 9 | 10 | map $binary_remote_addr $binary_remote_net { 11 | "~^(?P...).$" $net; # IPv4 /24 is first 3 of 4 byte (32-bit) number. 12 | "~^(?P........)........$" $net; # IPv6 /64 is first 8 of 16 byte (128-bit) number. 13 | default $binary_remote_addr; # Should never happen. Return IP. 14 | } 15 | 16 | 17 | # For include/cookies-only, decide action to take: [r]edirect, [p]ass, [f]ail. 18 | 19 | map "$cookie_u|$arg_cookietest" $cookietest_action { 20 | | r; # No cookie, no arg. 21 | ~^[^|] p; # Cookie. 22 | default f; # No cookie, arg. 23 | } 24 | 25 | 26 | # For include/response-headers, generate $x_frame_options 27 | map $x_frame_options_override $x_frame_options { 28 | "" ""; # Allow iframing by default. 29 | ALLOW ""; # Delete header if set to ALLOW. 30 | default $x_frame_options_override; # Otherwise use supplied value. 31 | } 32 | 33 | 34 | # Only pass through "Connection: Upgrade" if websockets are enabled. 35 | map "$websockets_override|$http_connection" $x_connection { 36 | "" ""; 37 | ALLOW|Upgrade $http_connection; 38 | } 39 | 40 | # Only pass through "Upgrade: websocket" if websockets are enabled. 41 | map "$websockets_override|$http_upgrade" $x_upgrade { 42 | "" ""; 43 | ALLOW|websocket $http_upgrade; 44 | } 45 | 46 | # Classify User-Agent into [b]ot/[t]est/[u]ser/[o]ther. Use the longest 47 | # possible unconditional substrings and keep this to under a few dozen 48 | # regexs. 49 | 50 | map $http_user_agent $user_agent_class { 51 | # Feed readers 52 | ~[fF]eed f; 53 | ~[nN]ews f; 54 | ~[bB]log f; 55 | ~*rss f; 56 | ~Apple-PubSub f; 57 | 58 | # Bots 59 | ~[bB]ot\b b; 60 | ~[cC]rawler\b b; 61 | ~[sS]pider\b b; 62 | "~Yahoo! Slurp" b; 63 | ~ia_archiver b; 64 | 65 | # Monitoring test traffic 66 | ~nagios-plugins t; 67 | ~Pingdom\.com t; 68 | ~HealthChecker t; 69 | 70 | # Users on browsers 71 | "~ MSIE " u; 72 | ~Gecko u; 73 | ~Safari/ u; 74 | ~Opera u; 75 | 76 | # Other 77 | default o; 78 | } 79 | 80 | 81 | # Does User-agent claim to be a mobile device? 82 | 83 | map $http_user_agent $is_mobile { 84 | # iPad claims to be mobile, but we disagree. 85 | ~\biPad\b n; 86 | 87 | ~Mobile y; 88 | default n; 89 | } 90 | 91 | 92 | # Parse Accept header for most-preferred mime type string, which will be the 93 | # first one mentioned without a score or with a score of 1.0. Failing that, 94 | # use first mentioned. Failing that, return "unknown/unknown"; 95 | 96 | map $http_accept $first_http_accept { 97 | "" ""; 98 | */* */*; 99 | "~\b(?P[a-z]+/[a-z*-]+)(,|;\s*q=1|$)" $type; 100 | "~\b(?P[a-z*]+/[a-z*-]+)\b" $type; 101 | default unknown/unknown; 102 | } 103 | 104 | 105 | # Parse first mime-type mentioned in Accept into [e]mpty, [w]ildcard, 106 | # [h]tml, [i]mage, [c]ss, [j]avascript, jso[n], [t]ext, [a]pplication, or 107 | # [o]ther. Use the longest possible unconditional substrings and keep this 108 | # to under a few dozen regexs. 109 | 110 | map $first_http_accept $prefer_mime_type { 111 | "" e; 112 | */* w; 113 | application/javascript j; 114 | application/json n; 115 | application/x-thrift r; 116 | application/x-thrift-compact f; 117 | image/jpeg i; 118 | image/png i; 119 | text/css c; 120 | text/html h; 121 | text/javascript j; 122 | ~^application/ a; 123 | ~^text/ t; 124 | ~^image/ i; 125 | default o; 126 | } 127 | 128 | 129 | # Generate a canonical Accept header suitable for passing to Ruby apps based 130 | # on preferred mime-type. 131 | 132 | map $prefer_mime_type $canonical_accept { 133 | h "text/html,application/xhtml+xml,*/*;q=0.1"; 134 | c "text/css,*/*;q=0.1"; 135 | n "application/json"; # Adding "*/*" here results in 405 errors. 136 | r "application/x-thrift"; 137 | f "application/x-thrift-compact"; 138 | j "text/javascript,application/javascript,*/*;q=0.1"; 139 | i "image/jpg,image/png,image/gif,*/*;q=0.1"; 140 | default "*/*"; 141 | } 142 | 143 | 144 | # Parse first two-letter language mentioned in Accept-Language (such as 145 | # "en") or return [_e]mpty, [_w]ildcard, or [_o]ther status. 146 | 147 | map $http_accept_language $prefer_language { 148 | "" _e; 149 | ~*^(?P[a-z][a-z])\b $lang; 150 | ~^\* _w; 151 | default _o; 152 | } 153 | 154 | 155 | # Remove everything through first dot in $host. 156 | 157 | map $host $domain_from_host { 158 | ~*^[^.]*\.(?P[a-z0-9-.]+\.[a-z]+)$ $domain; 159 | default unknown; 160 | } 161 | -------------------------------------------------------------------------------- /global.d/mime-types.conf: -------------------------------------------------------------------------------- 1 | # Mime Types: http://wiki.nginx.org/HttpCoreModule#types 2 | # 3 | # For files served from local disk, the returned Mime Type is usually based 4 | # on the filename's extension. 5 | 6 | default_type application/octet-stream; 7 | 8 | types { 9 | text/html html htm shtml; 10 | text/css css; 11 | text/xml xml; 12 | image/gif gif; 13 | image/jpeg jpeg jpg; 14 | application/x-javascript js; 15 | application/atom+xml atom; 16 | application/rss+xml rss; 17 | 18 | text/cache-manifest appcache mf; 19 | text/mathml mml; 20 | text/plain txt; 21 | text/vnd.sun.j2me.app-descriptor jad; 22 | text/vnd.wap.wml wml; 23 | text/x-component htc; 24 | 25 | image/png png; 26 | image/tiff tif tiff; 27 | image/vnd.wap.wbmp wbmp; 28 | image/x-icon ico; 29 | image/x-jng jng; 30 | image/x-ms-bmp bmp; 31 | image/svg+xml svg; 32 | 33 | application/font-woff woff; 34 | application/java-archive jar war ear; 35 | application/mac-binhex40 hqx; 36 | application/msword doc; 37 | application/pdf pdf; 38 | application/postscript ps eps ai; 39 | application/rtf rtf; 40 | application/vnd.ms-excel xls; 41 | application/vnd.ms-fontobject eot; 42 | application/vnd.ms-powerpoint ppt; 43 | application/vnd.wap.wmlc wmlc; 44 | application/vnd.wap.xhtml+xml xhtml; 45 | application/vnd.google-earth.kml+xml kml; 46 | application/vnd.google-earth.kmz kmz; 47 | application/x-7z-compressed 7z; 48 | application/x-cocoa cco; 49 | application/x-java-archive-diff jardiff; 50 | application/x-java-jnlp-file jnlp; 51 | application/x-makeself run; 52 | application/x-perl pl pm; 53 | application/x-pilot prc pdb; 54 | application/x-rar-compressed rar; 55 | application/x-redhat-package-manager rpm; 56 | application/x-sea sea; 57 | application/x-shockwave-flash swf; 58 | application/x-stuffit sit; 59 | application/x-tcl tcl tk; 60 | application/x-x509-ca-cert der pem crt; 61 | application/x-xpinstall xpi; 62 | application/zip zip; 63 | 64 | application/octet-stream bin exe dll; 65 | application/octet-stream deb; 66 | application/octet-stream dmg; 67 | application/octet-stream iso img; 68 | application/octet-stream msi msp msm; 69 | 70 | audio/midi mid midi kar; 71 | audio/mpeg mp3; 72 | audio/x-realaudio ra; 73 | 74 | video/3gpp 3gpp 3gp; 75 | video/mpeg mpeg mpg; 76 | video/quicktime mov; 77 | video/x-flv flv; 78 | video/x-mng mng; 79 | video/x-ms-asf asx asf; 80 | video/x-ms-wmv wmv; 81 | video/x-msvideo avi; 82 | 83 | font/ttf ttf; 84 | font/opentype otf; 85 | } 86 | -------------------------------------------------------------------------------- /global.d/proxy.conf: -------------------------------------------------------------------------------- 1 | # Proxy Module: http://wiki.nginx.org/HttpProxyModule 2 | 3 | proxy_intercept_errors on; 4 | recursive_error_pages on; 5 | 6 | include include/pretty-error-pages; 7 | 8 | # Use HTTP/1.1 to talk to upstreams. 9 | proxy_http_version 1.1; 10 | 11 | # Set up some limits on proxy timeouts and sizes. 12 | proxy_connect_timeout 2s; 13 | proxy_read_timeout 60s; 14 | proxy_send_timeout 10s; 15 | proxy_buffering on; 16 | proxy_buffers 64 4k; 17 | proxy_max_temp_file_size 25m; 18 | proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; 19 | 20 | # Set up proxy_cache for include/static-assets and include/cache-logged-out. 21 | proxy_cache off; 22 | proxy_cache_bypass $cookie_nocache; 23 | proxy_no_cache $cookie_nocache; 24 | proxy_cache_key $scheme://$host$request_uri; # Cache on the full URL. 25 | proxy_cache_min_uses 1; # Save on the first use. 26 | proxy_cache_revalidate on; 27 | proxy_cache_use_stale updating error timeout invalid_header http_500 http_502 http_503 http_504; 28 | 29 | proxy_cache_valid 200 301 1h; # Save good results for 1 hour by default. 30 | proxy_cache_valid 404 1m; # Only cache 404s for 1 minute. 31 | -------------------------------------------------------------------------------- /global.d/real-ip.conf: -------------------------------------------------------------------------------- 1 | # Real-IP Module: http://wiki.nginx.org/HttpRealipModule 2 | 3 | # Use the last non-whitelisted IP in X-Forwarded-For. 4 | real_ip_recursive on; 5 | real_ip_header X-Forwarded-For; 6 | #real_ip_header proxy_protocol; 7 | 8 | # Internal trusted IPs, such as load balancers that set X-Forwarded-For 9 | #set_real_ip_from 10.0.0.0/8; 10 | 11 | # Cloudflare IPs from: https://www.cloudflare.com/ips/ 12 | # Run: curl -s https://www.cloudflare.com/ips-v{4,6} | awk '{print "set_real_ip_from "$0";"}' 13 | 14 | # Cloudfront IPs from: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html 15 | # Run: curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | \ 16 | # jq -r '.prefixes[] | select(.service=="CLOUDFRONT") | .ip_prefix' | \ 17 | # awk '{print "set_real_ip_from "$0";"}' 18 | -------------------------------------------------------------------------------- /global.d/ssl-dhparam.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN DH PARAMETERS----- 2 | MIIBCAKCAQEA2bEWQuADm6R3Uc5bua2n3ibWOGFt1lZplnQzUIf6ti258a6iIUHO 3 | 107vn68Qs090VE+zE1spY99neXT1mlrBpDQzmKG7+h2WdwyfTeg1nn4pgdrj6XR5 4 | /asAKArick3YbOGZQ5+irhh/QNmLxVExasdsIYCQa7t1IudXqKBdWeMe2e2TKS/u 5 | keSOhxCOdlwTl9hkewsfe5mooabSVbd2TpVlIMhDW/op7W8rHJLB2ipnU+fW0fmr 6 | grQlr0lnQ/nMf/YMUmtt6mB9X20oB/wK8p9mVCuF2X1VMqOSt2QGGu6l3yvlUdf1 7 | NGkQKeh1tQ9OhLuohbNb53xr6C4d59BDowIBAg== 8 | -----END DH PARAMETERS----- 9 | -------------------------------------------------------------------------------- /global.d/ssl.conf: -------------------------------------------------------------------------------- 1 | # SSL Module: http://wiki.nginx.org/HttpSslModule 2 | 3 | # SSLv2 and SSLv3 are too weak. Disable them. 4 | 5 | ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 6 | 7 | # Cipher recommendation taken from 8 | # https://wiki.mozilla.org/Security/Server_Side_TLS, requiring RSA, and with 9 | # wildcards removed. 10 | 11 | ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA; 12 | ssl_prefer_server_ciphers on; 13 | 14 | # Allow SSL session resumption to skip part of handshake with a given client 15 | # if we've done it recently. 16 | 17 | ssl_session_cache shared:SSL:50m; # 4000 entries per 1meg 18 | ssl_session_timeout 10m; # Full handshake how often? 19 | 20 | # Use a 2048-bit dhparam. This is not sensitive. 21 | 22 | ssl_dhparam global.d/ssl-dhparam.pem; 23 | 24 | # Enable caching of OCSP validation from our CA and stapling it to our TLS 25 | # handshake response. 26 | 27 | #ssl_stapling on; 28 | #ssl_stapling_verify on; 29 | 30 | # Chain of intermediates required for ssl_stapling_verify, in order 31 | # from closest to our cert to the root. 32 | 33 | #ssl_trusted_certificate global.d/ssl-trusted.crt; 34 | 35 | # Buffer size of 1400 bytes fits in one MTU. This allows faster parsing of 36 | # responses, as the client doesn't need to wait for a 4k boundary, but adds 37 | # overhead. 38 | 39 | ssl_buffer_size 1400; 40 | -------------------------------------------------------------------------------- /global.d/upstream.conf: -------------------------------------------------------------------------------- 1 | # All upstreams for servers in nginx/sites.d/. Names are lower case, end in 2 | # "-upstream", and are listed in alphabetical order. 3 | 4 | upstream service1-upstream { 5 | least_conn; 6 | 7 | server 127.0.0.1:6000; 8 | 9 | keepalive 6; # per worker pool across all upstream servers 10 | } 11 | 12 | upstream service2-upstream { 13 | least_conn; 14 | 15 | server 127.0.0.1:7000; 16 | 17 | keepalive 6; # per worker pool across all upstream servers 18 | } 19 | 20 | upstream service3-upstream { 21 | least_conn; 22 | 23 | server 127.0.0.1:8000; 24 | 25 | keepalive 6; # per worker pool across all upstream servers 26 | } 27 | 28 | # Image resizing service (https://github.com/die-net/fotomat/) 29 | upstream fotomat-upstream { 30 | least_conn; 31 | 32 | server 127.0.0.1:3520; 33 | 34 | keepalive 6; # per worker pool across all upstream servers 35 | } 36 | -------------------------------------------------------------------------------- /global.d/userid.conf: -------------------------------------------------------------------------------- 1 | # UserID Module: http://wiki.nginx.org/HttpUseridModule 2 | 3 | # Set a long-lived "u" cookie to a random ID. This is used for analytics 4 | # and the A/B testing framework. By default, this is scoped to the current 5 | # hostname, but this should be widened to the parent domain (example.com, etc) 6 | # in each server block to get one consistent cookie across all subdomains. 7 | 8 | userid on; 9 | userid_name u; 10 | userid_expires max; 11 | 12 | 13 | # Generate $x_viewer_id (X-Viewer-Id header) based on $uid_got and 14 | # $uid_set. 15 | 16 | map $uid_got $x_viewer_id { 17 | "" $uid_set; 18 | default $uid_got; 19 | } 20 | -------------------------------------------------------------------------------- /include/akamai-client-ip: -------------------------------------------------------------------------------- 1 | # Include me in any server blocks where Akamai is used as the CDN to 2 | # properly log, rate-limit, and access-control based on client IP. 3 | # 4 | # The Akamai configuration must have "Optional Features" -> "Edge Services - 5 | # General" enabled and "True Client IP Header Name" set to 6 | # "Jood1xowian-IP". This is a secret header we use to tell if a request 7 | # came in from Akamai and what the original IP was if so. (Akamai has too 8 | # many IPs to list in set_real_ip_from.) 9 | # 10 | # Warning: Anyone who knows the string "Jood1xowian-IP" can spoof IPs to us! 11 | 12 | real_ip_header Jood1xowian-IP; 13 | real_ip_recursive off; 14 | set_real_ip_from 0.0.0.0/0; 15 | -------------------------------------------------------------------------------- /include/allow-cors: -------------------------------------------------------------------------------- 1 | # Include me if you'd like to allow a specific server or block to allow 2 | # cross-domain XMLHttpRequest, web fonts, etc. See global.d/map.conf and 3 | # include/response-headers for detail. 4 | 5 | set $x_access_control_allow_origin "*"; 6 | -------------------------------------------------------------------------------- /include/allow-websockets: -------------------------------------------------------------------------------- 1 | # Include me if you'd like to allow a specific server or block to allow 2 | # cross-domain XMLHttpRequest, web fonts, etc. See global.d/map.conf and 3 | # include/response-headers for detail. 4 | 5 | set $websockets_override ALLOW; 6 | -------------------------------------------------------------------------------- /include/assets-base: -------------------------------------------------------------------------------- 1 | # Included into various server blocks where we serve assets from S3. 2 | 3 | location /s3/ { 4 | return 404; 5 | } 6 | 7 | location /s3/stuff/ { 8 | include include/proxy-to-s3; 9 | include include/no-args; 10 | proxy_pass http://stuff-example-com.s3.amazonaws.com/; 11 | expires 30d; 12 | } 13 | 14 | location /s3/things/ { 15 | include include/proxy-to-s3; 16 | include include/no-args; 17 | include include/allow-cors; 18 | proxy_pass http://things-example-com.s3.amazonaws.com/; 19 | expires 30d; 20 | } 21 | 22 | location /s3/youtube/vi/ { 23 | include include/proxy-to-s3; 24 | include include/no-args; 25 | proxy_pass http://img.youtube.com/vi/; 26 | expires 30d; 27 | } 28 | 29 | # Paths with parameters like "=s80" or "=c240x160" on the end are 30 | # requests for resizing. Pass to fotomat. 31 | location ~ =p?w?[cs][0-9]*(?:x[0-9]*)?$ { 32 | include include/static-assets; 33 | include include/no-args; 34 | 35 | proxy_pass http://fotomat-upstream; 36 | 37 | expires 365d; 38 | proxy_cache_valid 200 7d; 39 | proxy_cache_valid 403 404 415 413 1h; 40 | } 41 | -------------------------------------------------------------------------------- /include/cache-locally: -------------------------------------------------------------------------------- 1 | # Mark content as cachable by nginx for 5 minutes, but not cacheable by 2 | # proxies or browsers. If cookies are sent by the upstream, it won't be 3 | # cached. 4 | 5 | include include/response-headers; 6 | 7 | proxy_hide_header Cache-Control; 8 | proxy_hide_header Pragma; 9 | proxy_hide_header Expires; 10 | 11 | # The combination "max-age=0,private,must-revalidate" should do the same 12 | # thing as "no-cache", except the latter has started to be interpreted as 13 | # "no-store" by some browsers, which we don't want here. 14 | 15 | add_header Cache-Control "max-age=0,private,must-revalidate"; 16 | add_header Expires "-1"; 17 | 18 | # Allow this content to be cached by this proxy. 19 | proxy_cache on; 20 | proxy_ignore_headers Expires Cache-Control; 21 | 22 | # Save good results for 5min. 23 | proxy_cache_valid 200 301 404 5m; 24 | -------------------------------------------------------------------------------- /include/cache-logged-out: -------------------------------------------------------------------------------- 1 | # Mark content as cachable by nginx for logged-out users, but not cacheable 2 | # by proxies or browsers, so if the user logs in, they'll start seeing 3 | # different content. 4 | 5 | include include/response-headers; 6 | 7 | proxy_hide_header Cache-Control; 8 | proxy_hide_header Pragma; 9 | proxy_hide_header Expires; 10 | 11 | # The combination "max-age=0,private,must-revalidate" should do the same 12 | # thing as "no-cache", except the latter has started to be interpreted as 13 | # "no-store" by some browsers, which we don't want here. 14 | 15 | add_header Cache-Control "max-age=0,private,must-revalidate"; 16 | add_header Expires "-1"; 17 | 18 | # Allow this content to be cached by this proxy. 19 | proxy_cache on; 20 | proxy_cache_key $prefer_mime_type-$scheme://$host$request_uri; # Cache on Accept plus the full URL. 21 | proxy_ignore_headers Expires Cache-Control; 22 | 23 | # But only if the user has no example-session cookie. 24 | proxy_cache_bypass $cookie_nocache $cookie_example_session; 25 | proxy_no_cache $cookie_nocache $cookie_example_session; 26 | 27 | # Save good results for 5min. 28 | proxy_cache_valid 200 301 404 5m; 29 | -------------------------------------------------------------------------------- /include/cloudflare-client-ip: -------------------------------------------------------------------------------- 1 | # Include me in any server blocks where CloudFlare is used as the CDN to 2 | # properly log, rate-limit, and access-control based on client IP. 3 | # 4 | # Warning: Anyone who knows the string "CF-Connecting-IP" can spoof IPs to 5 | # us! This isn't secure if non-CloudFlare IPs are allowed to connect to 6 | # either our ELB or our server instances directly. 7 | 8 | real_ip_header CF-Connecting-IP; 9 | real_ip_recursive off; 10 | set_real_ip_from 0.0.0.0/0; 11 | -------------------------------------------------------------------------------- /include/cookies-only: -------------------------------------------------------------------------------- 1 | # To lightly protect some parts of the site from stupid scrapers, only allow 2 | # this URL to be accessed if browser either has an existing "u" cookie or is 3 | # willing to accept one after a redirect. See $cookietest_action in 4 | # global.d/map.conf. 5 | # 6 | # WARNING: Only use this on URLs that are disallowed by robots.txt! 7 | 8 | if ($cookietest_action = "r") { 9 | return 302 $scheme://$host$uri?cookietest=1&$args; 10 | } 11 | 12 | if ($cookietest_action = "f") { 13 | return 400; 14 | } 15 | -------------------------------------------------------------------------------- /include/deny-abusive: -------------------------------------------------------------------------------- 1 | # For abusive countries/IPs, return 403 for some URLs. 2 | # TODO: Remove me when we get a CAPTCHA. 3 | if ($x_limit_type = "a") { 4 | return 403; 5 | } 6 | -------------------------------------------------------------------------------- /include/deny-iframing: -------------------------------------------------------------------------------- 1 | # Include me if you'd like to deny a specific server or block from being 2 | # iframed. See global.d/map.conf and include/response-headers for detail. 3 | 4 | set $x_frame_options_override SAMEORIGIN; 5 | -------------------------------------------------------------------------------- /include/down-for-maintenance: -------------------------------------------------------------------------------- 1 | # Include me into location blocks (NOT server blocks!) where we're 2 | # temporarily down for maintenance. Adding "include 3 | # include/down-for-maintenance" is okay to do manually on the proxies, as 4 | # long as getting rid of it is done by redeploying. 5 | # 6 | # This allows company internal IPs ($x_limit_type of "i") to access and 7 | # throws a 520 error otherwise, which is translated in global.d/proxy.conf 8 | # into a 503 with the pretty maintenance page. 9 | 10 | if ($x_limit_type != "i") { 11 | return 520; 12 | } 13 | -------------------------------------------------------------------------------- /include/fastcgi-params: -------------------------------------------------------------------------------- 1 | fastcgi_param QUERY_STRING $query_string; 2 | fastcgi_param REQUEST_METHOD $request_method; 3 | fastcgi_param CONTENT_TYPE $content_type; 4 | fastcgi_param CONTENT_LENGTH $content_length; 5 | 6 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 7 | fastcgi_param SCRIPT_NAME $fastcgi_script_name; 8 | fastcgi_param PATH_INFO $fastcgi_path_info; 9 | fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; 10 | fastcgi_param REQUEST_URI $request_uri; 11 | fastcgi_param DOCUMENT_URI $document_uri; 12 | fastcgi_param DOCUMENT_ROOT $document_root; 13 | fastcgi_param SERVER_PROTOCOL $server_protocol; 14 | 15 | fastcgi_param GATEWAY_INTERFACE CGI/1.1; 16 | fastcgi_param SERVER_SOFTWARE nginx; 17 | 18 | fastcgi_param REMOTE_ADDR $remote_addr; 19 | fastcgi_param REMOTE_PORT $remote_port; 20 | fastcgi_param SERVER_ADDR $server_addr; 21 | fastcgi_param SERVER_PORT $server_port; 22 | fastcgi_param SERVER_NAME $server_name; 23 | 24 | fastcgi_param HTTPS $https; 25 | 26 | # PHP only, required if PHP was built with --enable-force-cgi-redirect 27 | fastcgi_param REDIRECT_STATUS 200; 28 | -------------------------------------------------------------------------------- /include/forceerror-cookie: -------------------------------------------------------------------------------- 1 | if ($cookie_forceerror = "403") { 2 | return 403; 3 | } 4 | 5 | if ($cookie_forceerror = "404") { 6 | return 404; 7 | } 8 | 9 | if ($cookie_forceerror = "444") { 10 | return 444; 11 | } 12 | 13 | if ($cookie_forceerror = "500") { 14 | return 500; 15 | } 16 | 17 | if ($cookie_forceerror = "520") { 18 | return 520; 19 | } 20 | -------------------------------------------------------------------------------- /include/get-only: -------------------------------------------------------------------------------- 1 | # Include me into server or location blocks where only the GET or HEAD 2 | # methods are allowed. Use this on read-only content or on redirects, where 3 | # redirecting non-GET won't work right. 4 | 5 | if ($request_method !~ ^(?:GET|HEAD)$) { 6 | return 405; 7 | } 8 | -------------------------------------------------------------------------------- /include/insecure-only: -------------------------------------------------------------------------------- 1 | # Only allow this URL to be accessed insecurely. Redirect otherwise. 2 | if ($scheme != "http") { 3 | return 301 http://$host$request_uri; 4 | } 5 | -------------------------------------------------------------------------------- /include/no-args: -------------------------------------------------------------------------------- 1 | # Return 404 if there were args supplied. 2 | if ($args) { 3 | return 404; 4 | } 5 | -------------------------------------------------------------------------------- /include/no-cache: -------------------------------------------------------------------------------- 1 | # Disable almost all browser and proxy caching, in all modern browsers. 2 | # Allows content to be stored on disk and revalidated using 3 | # If-Modified-Since or If-None-Match and the use of the "back" button. 4 | # 5 | # WARNING: This is not safe to guarantee "logout" to be secure. 6 | 7 | include include/response-headers; 8 | 9 | proxy_hide_header Cache-Control; 10 | proxy_hide_header Pragma; 11 | proxy_hide_header Expires; 12 | 13 | # The combination "max-age=0,must-revalidate" should do the same thing as 14 | # "no-cache", except the latter has started to be interpreted as "no-store" 15 | # by some browsers, which we don't want here. 16 | 17 | add_header Cache-Control "max-age=0,must-revalidate"; 18 | add_header Expires "-1"; 19 | -------------------------------------------------------------------------------- /include/no-store: -------------------------------------------------------------------------------- 1 | # Disable all browser and proxy caching, including back button, in 2 | # all modern browsers. Required for "logout" to be secure. 3 | # 4 | # WARNING: If used on more than a few elements of a page, this will slow 5 | # down the user experience significantly. 6 | 7 | include include/response-headers; 8 | 9 | proxy_hide_header Cache-Control; 10 | proxy_hide_header Pragma; 11 | proxy_hide_header Expires; 12 | proxy_hide_header ETag; 13 | proxy_hide_header Last-Modified; 14 | 15 | add_header Cache-Control "no-cache,no-store,max-age=0,must-revalidate"; 16 | add_header Expires "-1"; 17 | -------------------------------------------------------------------------------- /include/pretty-error-pages: -------------------------------------------------------------------------------- 1 | # Set up pretty error pages for most error codes. Include me after you 2 | # override any of these in a location block. 3 | 4 | error_page 403 /proxyerror/403.html; 5 | error_page 404 /proxyerror/404.html; 6 | error_page 413 /proxyerror/413.html; 7 | error_page 418 /proxyerror/418.html; 8 | error_page 429 /proxyerror/429.html; 9 | error_page 500 502 503 504 /proxyerror/50x.html; 10 | 11 | # Turn 520 into a 503 and show the pretty down-for-maintenance page. 12 | error_page 520 =503 /proxyerror/520.html; 13 | -------------------------------------------------------------------------------- /include/proxy-headers: -------------------------------------------------------------------------------- 1 | # Only pass a subset of request headers. See include/map for the $x_geo 2 | # and x_viewer_id values. In alphabetical order to make sniffing easier. 3 | 4 | proxy_set_header Accept $canonical_accept; 5 | proxy_set_header Accept-Charset ""; # Don't negotiate charset. 6 | proxy_set_header Accept-Encoding ""; # Disable gzip from upstream. 7 | proxy_set_header Accept-Language ""; # Don't negotiate language. 8 | proxy_set_header Authorization $http_authorization; 9 | proxy_set_header Content-Length $http_content_length; 10 | proxy_set_header Content-Type $http_content_type; 11 | proxy_set_header Connection $x_connection; 12 | proxy_set_header Cookie $http_cookie; 13 | proxy_set_header Host $host; 14 | proxy_set_header Origin $http_origin; 15 | proxy_set_header If-Modified-Since $http_if_modified_since; 16 | proxy_set_header If-None-Match $http_if_none_match; 17 | proxy_set_header Sec-Websocket-Key $http_sec_websocket_key; 18 | proxy_set_header Sec-Websocket-Version $http_sec_websocket_version; 19 | proxy_set_header Upgrade $x_upgrade; 20 | proxy_set_header User-Agent $http_user_agent; 21 | proxy_set_header x-amz-sns-message-type $http_x_amz_sns_message_type; 22 | proxy_set_header x-amz-sns-topic-arn $http_x_amz_sns_topic_arn; 23 | proxy_set_header X-CSRF-Token $http_x_csrf_token; 24 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 25 | proxy_set_header X-Forwarded-Protocol $scheme; 26 | proxy_set_header X-HTTP-Method-Override $http_x_http_method_override; 27 | proxy_set_header X-Real-IP $remote_addr; 28 | proxy_set_header X-Requested-With $http_x_requested_with; 29 | proxy_set_header X-Geo $x_geo; 30 | proxy_set_header X-Limit-Type $x_limit_type; 31 | #proxy_set_header X-Viewer-ID $x_viewer_id; 32 | -------------------------------------------------------------------------------- /include/proxy-headers-external: -------------------------------------------------------------------------------- 1 | # Only pass through very limited headers. Don't list Host here, so we send 2 | # the proxy_pass hostname to the third-party. 3 | 4 | proxy_pass_request_headers off; 5 | proxy_set_header Accept */*; 6 | proxy_set_header Accept-Charset ""; 7 | proxy_set_header Accept-Encoding gzip; 8 | proxy_set_header Accept-Language ""; 9 | proxy_set_header Connection $x_connection; 10 | proxy_set_header Content-Length $http_content_length; 11 | proxy_set_header Content-Type $http_content_type; 12 | proxy_set_header Sec-Websocket-Key $http_sec_websocket_key; 13 | proxy_set_header Sec-Websocket-Version $http_sec_websocket_version; 14 | proxy_set_header Upgrade $x_upgrade; 15 | proxy_set_header User-Agent $http_user_agent; 16 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 17 | -------------------------------------------------------------------------------- /include/proxy-headers-minimal: -------------------------------------------------------------------------------- 1 | # Aggressively filter headers to the minimal set required to answer a 2 | # request. Only pass a subset of request headers. See include/map for the 3 | # $x_geo and x_viewer_id values. In alphabetical order to make sniffing 4 | # easier. 5 | 6 | proxy_set_header Accept $canonical_accept; 7 | proxy_set_header Accept-Charset ""; 8 | proxy_set_header Accept-Encoding ""; # Disable gzip from upstream. 9 | proxy_set_header Accept-Language ""; 10 | proxy_set_header Content-Length $http_content_length; 11 | proxy_set_header Content-Type $http_content_type; 12 | proxy_set_header Connection $x_connection; 13 | proxy_set_header Cookie ""; 14 | proxy_set_header Host $host; 15 | proxy_set_header Origin ""; 16 | proxy_set_header If-Modified-Since ""; 17 | proxy_set_header If-None-Match ""; 18 | proxy_set_header Sec-Websocket-Key $http_sec_websocket_key; 19 | proxy_set_header Sec-Websocket-Version $http_sec_websocket_version; 20 | proxy_set_header Upgrade $x_upgrade; 21 | proxy_set_header User-Agent ""; 22 | proxy_set_header X-Forwarded-For ""; 23 | proxy_set_header X-Forwarded-Protocol $scheme; 24 | proxy_set_header X-HTTP-Method-Override ""; 25 | proxy_set_header X-Real-IP $remote_addr; 26 | proxy_set_header X-Requested-With ""; 27 | proxy_set_header X-Geo $x_geo; 28 | -------------------------------------------------------------------------------- /include/proxy-to-s3: -------------------------------------------------------------------------------- 1 | # Include me in location blocks where there's a proxy_pass to Amazon S3. 2 | # Also required in the block is an "expires 1h" or similar. 3 | 4 | # S3 returns 403 when files are missing. Translate to 404 instead. 5 | error_page 403 =404 /proxyerror/404.html; 6 | # Add back use of pretty error pages for other errors. 7 | include include/pretty-error-pages; 8 | 9 | # We only respond to HEAD or GET. 10 | include include/get-only; 11 | 12 | # We are definitely static content. 13 | include include/static-assets; 14 | 15 | # Ignore host header and args for cache key. Cache based on first 16 | # server_name and path. 17 | proxy_cache_key http://$server_name$uri; 18 | 19 | # And we want to pass S3 its own hostname, not ours. 20 | include include/proxy-headers-external; 21 | -------------------------------------------------------------------------------- /include/redirect-to-secure: -------------------------------------------------------------------------------- 1 | # Only allow this URL to be accessed securely. Redirect otherwise. 2 | # Warning: This may result in data being sent in the clear. Use 3 | # include/secure-only on POSTs and sensitive locations. 4 | 5 | if ($scheme != "https") { 6 | return 301 https://$host$request_uri; 7 | } 8 | -------------------------------------------------------------------------------- /include/response-headers: -------------------------------------------------------------------------------- 1 | # Using proxy_hide_header or add_header in any server or location block will 2 | # clear these unless you include them again. 3 | 4 | proxy_hide_header Access-Control-Allow-Origin; # Sent by proxy only 5 | proxy_hide_header Alternate-Protocol; # Sent by proxy only 6 | proxy_hide_header P3P; # Sent by proxy only 7 | proxy_hide_header Strict-Transport-Security; # Sent by proxy only 8 | proxy_hide_header X-AspNet-Version; # ASP advertising 9 | proxy_hide_header X-Frame-Options; # Sent by proxy only 10 | proxy_hide_header X-Log; # Sent to proxy 11 | proxy_hide_header X-Powered-By; # ASP/PHP advertising 12 | proxy_hide_header X-Rack-Cache; # Sent to proxy 13 | proxy_hide_header X-Request-Id; # Sent to proxy 14 | proxy_hide_header X-Runtime; # Sent to proxy 15 | proxy_hide_header X-XSS-Protection; # Sent by proxy only 16 | 17 | # add CORS header for XMLHttpRequest, web fonts, etc. 18 | add_header Access-Control-Allow-Origin $x_access_control_allow_origin; 19 | 20 | # Ask IE 8+, Safari 4+, Chrome 4+, Firefox 3.6.9+ to control framing. 21 | # See global.d/map.conf and include/allow-iframing. 22 | add_header X-Frame-Options $x_frame_options; 23 | 24 | # Ask IE 8+, Safari, Chrome to not render reflected XSS that they identify. 25 | add_header X-XSS-Protection '1; mode=block'; 26 | -------------------------------------------------------------------------------- /include/retry-404s: -------------------------------------------------------------------------------- 1 | # Include me in server or location blocks where 404s shouldn't be 2 | # authorative, but should instead be retried on multiple upstreams. 3 | # (e.g. during deploys) 4 | 5 | proxy_next_upstream error timeout invalid_header http_404 http_500 http_502 http_503 http_504; 6 | -------------------------------------------------------------------------------- /include/secure-only: -------------------------------------------------------------------------------- 1 | # Only allow this URL to be accessed securely. Throw a 404 otherwise; it 2 | # isn't safe to accept insecure incoming links, then redirect. 3 | if ($scheme != "https") { 4 | return 404; 5 | } 6 | -------------------------------------------------------------------------------- /include/server-base: -------------------------------------------------------------------------------- 1 | # Include me into all server blocks. 2 | 3 | location /apple-touch-icon { 4 | allow all; 5 | 6 | include include/static-assets; 7 | expires 30d; 8 | } 9 | 10 | location = /crossdomain.xml { 11 | root /etc/nginx/root/shared; 12 | 13 | allow all; 14 | 15 | include include/static-assets; 16 | expires 12h; 17 | 18 | try_files /crossdomain-$host.xml /crossdomain-wildcard.$domain_from_host.xml /crossdomain.xml =404; 19 | } 20 | 21 | location = /favicon.ico { 22 | allow all; 23 | 24 | log_not_found on; 25 | 26 | include include/static-assets; 27 | expires 30d; 28 | } 29 | 30 | location = /debug { 31 | return 404; 32 | } 33 | 34 | location /debug/ { 35 | return 404; 36 | } 37 | 38 | location = /internal { 39 | return 404; 40 | } 41 | 42 | location /internal/ { 43 | return 404; 44 | } 45 | 46 | location /proxyerror/ { 47 | allow all; 48 | 49 | log_not_found on; 50 | ssi on; 51 | } 52 | 53 | location = /robots.txt { 54 | root /etc/nginx/root/shared; 55 | 56 | allow all; 57 | 58 | include include/static-assets; 59 | expires 12h; 60 | 61 | try_files /robots-$host.txt /robots-wildcard.$domain_from_host.txt /robots.txt =404; 62 | } 63 | 64 | # Paths with parameters like "=s80" or "=c240x160" on the end are requests 65 | # for resizing. Pass to fotomat. Responses are cached for a week by 66 | # default; cache-control and expires headers are respected to change that. 67 | location ~ =p?w?[cs][0-9]*(?:x[0-9]*)?$ { 68 | include include/get-only; 69 | include include/no-args; 70 | 71 | proxy_pass http://fotomat-upstream; 72 | 73 | proxy_cache on; 74 | proxy_cache_valid 200 7d; 75 | proxy_cache_valid 403 404 413 415 1h; 76 | } 77 | -------------------------------------------------------------------------------- /include/static-assets: -------------------------------------------------------------------------------- 1 | # Mark assets as cachable by proxies, disabling "u" cookie support. Use in 2 | # combination with the "expires" command to define the duration that it can 3 | # be cached. Also allows the use of ETag/Last-Modified and 4 | # If-None-Match/If-Modified-Since if those are supported by the upstream. 5 | # 6 | # WARNING: This content shouldn't use cookies or vary based on anything not 7 | # found in the URL. Don't use on URLs requiring login! 8 | 9 | include include/response-headers; 10 | 11 | # POSTs to static assets don't make sense. 12 | include include/get-only; 13 | 14 | proxy_hide_header Cache-Control; 15 | proxy_hide_header Expires; 16 | proxy_hide_header Pragma; 17 | proxy_hide_header Set-Cookie; 18 | 19 | # Allow content to be cacheable by proxies. 20 | add_header Cache-Control "public"; 21 | 22 | # Disable tracking cookies on cacheable content 23 | userid off; 24 | 25 | # Allow this content to be cached by this proxy. 26 | proxy_cache on; 27 | proxy_ignore_headers Expires Cache-Control Set-Cookie; 28 | 29 | # When serving from disk, look for a .gz first and serve it if it exists. 30 | gzip_static on; 31 | 32 | # Allow a much higher request rate for static assets. 33 | limit_req zone=fast_limit_buckets burst=5000; 34 | -------------------------------------------------------------------------------- /listen/example.com: -------------------------------------------------------------------------------- 1 | # Include me in server blocks where the domain is *.example.com and we want 2 | # to answer both http and https requests. 3 | 4 | listen 80; 5 | listen [::]:80; 6 | listen 443 ssl; 7 | listen [::]:443 ssl; 8 | 9 | # This is the default certificate in global.d/default_server.conf. Save 10 | # memory by not defining it again unnecessarily: 11 | #ssl_certificate /etc/ssl-example/wildcard.example.com.crt; 12 | #ssl_certificate_key /etc/ssl-example/wildcard.example.com.key; 13 | 14 | userid_domain example.com; 15 | 16 | root /etc/nginx/root/example.com; 17 | 18 | include include/server-base; 19 | -------------------------------------------------------------------------------- /listen/example.org: -------------------------------------------------------------------------------- 1 | # Include me in server blocks where the domain is *.example.org and we want 2 | # to answer both http and https requests. 3 | 4 | listen 80; 5 | listen [::]:80; 6 | listen 443 ssl; 7 | listen [::]:443 ssl; 8 | 9 | # Override the default certificate in global.d/default_server.conf: 10 | ssl_certificate /etc/ssl-example/wildcard.example.org.crt; 11 | ssl_certificate_key /etc/ssl-example/wildcard.example.org.key; 12 | 13 | userid_domain example.org; 14 | 15 | root /etc/nginx/root/example.org; 16 | 17 | include include/server-base; 18 | -------------------------------------------------------------------------------- /listen/misc: -------------------------------------------------------------------------------- 1 | # Include me in server blocks where the DNS points to that IP, where domain 2 | # is not *.example.com, and we'll only be serving http. 3 | # 4 | # Note that attempting to use https for any of these hostnames will result 5 | # in an SSL warning, but after clicking through that, it will eventually 6 | # redirect properly. 7 | 8 | listen 80; 9 | listen [::]:80; 10 | listen 443 ssl; 11 | listen [::]:443 ssl; 12 | 13 | # This is the default certificate in global.d/default_server.conf. Save 14 | # memory by not defining it again unnecessarily: 15 | #ssl_certificate /etc/ssl-example/wildcard.example.com.crt; 16 | #ssl_certificate_key /etc/ssl-example/wildcard.example.com.key; 17 | 18 | include include/server-base; 19 | -------------------------------------------------------------------------------- /listen/redirector: -------------------------------------------------------------------------------- 1 | # Include me in server blocks where the DNS points to that IP, where domain 2 | # is not *.example.com, and we'll only be serving http redirects. 3 | # 4 | # Note that attempting to use https for any of these hostnames will result 5 | # in an SSL warning, but after clicking through that, it will eventually 6 | # redirect properly. 7 | 8 | listen 80; 9 | listen [::]:80; 10 | listen 443 ssl; 11 | listen [::]:443 ssl; 12 | 13 | # This is the default certificate in global.d/default_server.conf. Save 14 | # memory by not defining it again unnecessarily: 15 | #ssl_certificate /etc/ssl-example/wildcard.example.com.crt; 16 | #ssl_certificate_key /etc/ssl-example/wildcard.example.com.key; 17 | 18 | # Don't try to redirect anything but HEAD and GET. 19 | include include/get-only; 20 | 21 | # Explicitly allow all redirects to be crawled, don't rely on 301 of 22 | # /robots.txt. 23 | location = /robots.txt { 24 | try_files /robots-redirector.txt =404; 25 | } 26 | -------------------------------------------------------------------------------- /nginx.conf: -------------------------------------------------------------------------------- 1 | # Main Module: http://wiki.nginx.org/NginxHttpMainModule 2 | 3 | # Use Nginx 1.12's module mechanism to load optional modules. For older 4 | # Nginx, you'll have to compile these in. 5 | load_module /usr/lib/nginx/modules/ngx_http_geoip_module.so; 6 | load_module /usr/lib/nginx/modules/ngx_stream_geoip_module.so; 7 | 8 | user nginx; 9 | 10 | pid /var/run/nginx.pid; 11 | error_log /var/log/nginx/error.log; 12 | 13 | # How many child processes to spawn to handle requests. Should at least be 14 | # number of non-HT cores available. 15 | worker_processes auto; 16 | 17 | # For safety, make sure the kernel allows us to use at least 18 | # worker_processes * worker_connections * 2 + 100 filedescriptors. 19 | worker_rlimit_nofile 262144; 20 | 21 | # Events Module: http://wiki.nginx.org/NginxHttpEventsModule 22 | 23 | events { 24 | # epoll is the scalable Linux event mechanism. Die if we can't use it. 25 | use epoll; 26 | 27 | # Total allowed connections is worker_processes * worker_connections. 28 | # Expect to run into problems at 60-70% of that; accept() mutex load 29 | # balancing isn't perfect. 30 | worker_connections 65536; 31 | 32 | # Reduce overhead by repeatedly accept()ing until accept queue is empty. 33 | multi_accept on; 34 | 35 | # If on Linux < 3.9, "reuseport" is unavailable, so uncomment this to 36 | # avoid thundering herd on accept(). One worker accept()s as fast as it 37 | # can for 20ms, then all workers wake up and try to take mutex. 38 | #accept_mutex on; 39 | #accept_mutex_delay 20ms; 40 | } 41 | 42 | 43 | # HTTP Core Module: http://wiki.nginx.org/NginxHttpCoreModule 44 | 45 | http { 46 | # Don't mention which NginX version we are running in responses. 47 | server_tokens off; 48 | 49 | # Which DNS resolvers to use for outbound HTTP connections. 50 | # "172.16.0.23" is Amazon's "Magic" DNS server. 51 | resolver 172.16.0.23; 52 | resolver_timeout 5s; 53 | 54 | # Disable nagle and try to coalesce TCP packets. 55 | tcp_nodelay on; 56 | tcp_nopush on; 57 | 58 | # Send large chunks of local files without copying to userspace. 59 | sendfile on; 60 | sendfile_max_chunk 1m; 61 | 62 | # Don't let a client get crazy with Range headers. 63 | max_ranges 10; 64 | 65 | # Allow connections to stay open after a response in case the client 66 | # wants to send another request. Claim to allow 4 minutes (NAT devices 67 | # commonly timeout in 5 min), actually allow an extra 5 seconds just in 68 | # case. 69 | keepalive_timeout 245 240; 70 | 71 | # Chrome preconnects to servers it thinks it might use soon. Match 72 | # keepalive_timeout here. This is total time to wait for complete 73 | # headers. 74 | client_header_timeout 4m; 75 | 76 | # How long do we wait for another packet of the request body to arrive? 77 | client_body_timeout 20s; 78 | 79 | # Allow POSTs of 10 megs. 80 | client_max_body_size 10m; 81 | 82 | # How long do we wait for another 4k of the response to be ACKed? 83 | send_timeout 20s; 84 | 85 | # If we timeout an incomplete response, skip FIN_WAIT1 and send RST. 86 | reset_timedout_connection on; 87 | 88 | # Don't send port numbers for odd ports. 89 | port_in_redirect off; 90 | 91 | # Default filename when URI specifies a directory. 92 | index index.html; 93 | 94 | # Allow more server_names than default limit. 95 | server_names_hash_max_size 4096; 96 | server_names_hash_bucket_size 512; 97 | 98 | # Allow larger maps than default. 99 | map_hash_max_size 2048; 100 | map_hash_bucket_size 128; 101 | 102 | # Allow more variables than default. 103 | variables_hash_max_size 1024; 104 | variables_hash_bucket_size 128; 105 | 106 | # Where to store tempfiles. 107 | client_body_temp_path /var/cache/nginx/nginx_client_temp 1 2; 108 | proxy_temp_path /var/cache/nginx/nginx_proxy_temp 1 2; 109 | fastcgi_temp_path /var/cache/nginx/nginx_fastcgi_temp 1 2; 110 | 111 | # Set up cache. (25 meg RAM = ~195,000 objects.) 112 | proxy_cache_path /var/cache/nginx/nginx_proxy_cache keys_zone=on:25m max_size=20g levels=1:2 inactive=1d; 113 | 114 | # Define a fast rate-limit bucket for use in acl/deny-all and include/static-assets. 115 | limit_req_zone $binary_remote_net zone=fast_limit_buckets:10m rate=100r/s; 116 | 117 | # Load global config from global.d/. 118 | include global.d/*.conf; 119 | 120 | # Load per-site config from sites.d/. 121 | include sites.d/*.conf; 122 | } 123 | -------------------------------------------------------------------------------- /root/README: -------------------------------------------------------------------------------- 1 | A root is a set of branding elements served by NginX, and must include: 2 | 3 | /favicon.ico - Default favicon if no meta icon header sent 4 | 5 | /apple-touch-icon*.png - Various icons asked for by iOS 6 | 7 | /proxyerror/403.html - Permission denied 8 | /proxyerror/404.html - Not found 9 | /proxyerror/413.html - Your POST is too big (> 10 megabytes) 10 | /proxyerror/418.html - The site you asked for is not configured 11 | /proxyerror/429.html - You've made too many requests lately and hit our rate-limit. 12 | /proxyerror/50x.html - Server error, unknown cause 13 | /proxyerror/520.html - We've taken the site down for maintenance 14 | 15 | 16 | The "shared" root is a special case and serves files for all roots: 17 | 18 | /robots-$host.txt - When user requests /robots.txt, we check if there is a host-specific one first. 19 | /robots-$domain.txt - When no $host found, subdomain up to the first dot is cut off and tried. 20 | /robots.txt - When neither of the above is found, this is served. 21 | 22 | /crossdomain-$host.xml - Same as above, for /crossdomain.xml. 23 | /crossdomain-$domain.xml 24 | /crossdomain.xml 25 | 26 | /google*.html - Proof of domain ownership for various Google accounts. 27 | -------------------------------------------------------------------------------- /root/example.com/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/die-net/nginx-config-example/6b30f42265e766ba5e28e895bb99a0ad2ae04f63/root/example.com/apple-touch-icon.png -------------------------------------------------------------------------------- /root/example.com/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/die-net/nginx-config-example/6b30f42265e766ba5e28e895bb99a0ad2ae04f63/root/example.com/favicon.ico -------------------------------------------------------------------------------- /root/example.com/proxyerror/403.html: -------------------------------------------------------------------------------- 1 | 403 Forbidden 2 | 3 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/404.html: -------------------------------------------------------------------------------- 1 | 404 Not Found 2 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/413.html: -------------------------------------------------------------------------------- 1 | 413 Upload too large 2 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/418.html: -------------------------------------------------------------------------------- 1 | 418 I'm a teapot 2 | 3 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/429.html: -------------------------------------------------------------------------------- 1 | 429 Too many requests 2 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/50x.html: -------------------------------------------------------------------------------- 1 | 50x Internal server error 2 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/520.html: -------------------------------------------------------------------------------- 1 | 520 Down for maintainence 2 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/blank.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ... 4 | 5 | 6 | -------------------------------------------------------------------------------- /root/example.com/proxyerror/nocache.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Set/Unset nocache cookie 5 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /root/example.org/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/die-net/nginx-config-example/6b30f42265e766ba5e28e895bb99a0ad2ae04f63/root/example.org/apple-touch-icon.png -------------------------------------------------------------------------------- /root/example.org/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/die-net/nginx-config-example/6b30f42265e766ba5e28e895bb99a0ad2ae04f63/root/example.org/favicon.ico -------------------------------------------------------------------------------- /root/example.org/proxyerror/403.html: -------------------------------------------------------------------------------- 1 | 403 Forbidden 2 | 3 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/404.html: -------------------------------------------------------------------------------- 1 | 404 Not Found 2 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/413.html: -------------------------------------------------------------------------------- 1 | 413 Upload too large 2 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/418.html: -------------------------------------------------------------------------------- 1 | 418 I'm a teapot 2 | 3 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/429.html: -------------------------------------------------------------------------------- 1 | 429 Too many requests 2 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/50x.html: -------------------------------------------------------------------------------- 1 | 50x Internal server error 2 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/520.html: -------------------------------------------------------------------------------- 1 | 520 Down for maintainence 2 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/blank.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ... 4 | 5 | 6 | -------------------------------------------------------------------------------- /root/example.org/proxyerror/nocache.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Set/Unset nocache cookie 5 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /root/shared/crossdomain.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /root/shared/robots-example.com.txt: -------------------------------------------------------------------------------- 1 | # Redirects for everyone! 2 | -------------------------------------------------------------------------------- /root/shared/robots-www.example.com.txt: -------------------------------------------------------------------------------- 1 | # Allow everyone to see our site! 2 | -------------------------------------------------------------------------------- /root/shared/robots-www.example.org.txt: -------------------------------------------------------------------------------- 1 | # Allow everyone to see our other site! 2 | -------------------------------------------------------------------------------- /root/shared/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: / 3 | -------------------------------------------------------------------------------- /sites.d/admin.example.com.conf: -------------------------------------------------------------------------------- 1 | # admin.example.com is a internal-only site. 2 | 3 | server { 4 | include listen/example.com; 5 | 6 | server_name 7 | admin.example.com 8 | ; 9 | 10 | include acl/allow-internal; 11 | include acl/deny-all; 12 | 13 | location / { 14 | proxy_pass http://service3-upstream/; 15 | include include/no-cache; 16 | } 17 | 18 | location /assets/ { 19 | proxy_pass http://service3-upstream/assets/; 20 | include include/static-assets; 21 | expires 1h; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sites.d/wildcard.example.com.conf: -------------------------------------------------------------------------------- 1 | # Redirects for *.example.com: Only serve 301s and 40x errors from here. 2 | 3 | server { 4 | include listen/example.com; 5 | 6 | server_name 7 | example.com 8 | m.example.com 9 | ; 10 | 11 | location / { 12 | include include/get-only; 13 | return 301 http://www.example.com$request_uri; 14 | } 15 | } 16 | 17 | # Redirect www.*.example.com to *.example.com to help with typos. Nginx 18 | # server_name rules process regular expressions last, so any static name 19 | # will override this. 20 | 21 | server { 22 | include listen/example.com; 23 | 24 | # Server_name regexp captures matching part after "www." into $domain. 25 | server_name ~^www\.?(?P[a-z0-9_-]+\.example\.com)$; 26 | 27 | location / { 28 | # Issue a 301 to the same URL without the "www.". 29 | include include/get-only; 30 | return 301 $scheme://$domain$request_uri; 31 | } 32 | } 33 | 34 | # Redirect http://*.example.com/ to http://www.example.com/. This must be a regexp 35 | # match, after the www.*.example.com redirect, in the same file. 36 | 37 | server { 38 | include listen/example.com; 39 | 40 | server_name ~\.example\.com$; 41 | 42 | location / { 43 | include include/get-only; 44 | return 301 $scheme://www.example.com$request_uri; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /sites.d/wildcard.example.org.conf: -------------------------------------------------------------------------------- 1 | # Redirects for *.example.org: Only serve 301s and 40x errors from here. 2 | 3 | server { 4 | include listen/example.org; 5 | 6 | include include/cloudflare-client-ip; 7 | 8 | server_name .example.org; 9 | 10 | location / { 11 | include include/get-only; 12 | return 301 https://www.example.org$request_uri; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /sites.d/www.example.com.conf: -------------------------------------------------------------------------------- 1 | # Simple URL direction from case-insensitive exact-match paths to const 2 | # targets. Arguments are preserved. Add more complex redirect rules as 3 | # their own location block. 4 | map $uri $redirect_www_example_com { 5 | default ""; 6 | 7 | # Matches in alphabetical order. 8 | /foo https://www.example.com/bar; 9 | /thing1 https://www.example.org/thing2; 10 | } 11 | 12 | server { 13 | include listen/example.com; 14 | 15 | include include/cloudflare-client-ip; 16 | 17 | server_name 18 | www.example.com 19 | ; 20 | 21 | # If redirect found, return 301 to new target, preserving args. 22 | if ($redirect_www_example_com) { 23 | return 301 $redirect_www_example_com$is_args$args; 24 | } 25 | 26 | location / { 27 | include include/redirect-to-secure; 28 | 29 | include include/cache-locally; 30 | 31 | proxy_pass http://service1-upstream/; 32 | } 33 | 34 | location /assets/ { 35 | include include/static-assets; 36 | expires 365d; 37 | 38 | proxy_pass http://service1-upstream/assets/; 39 | } 40 | 41 | location ~ ^/qwerty/(?P[^/]*) { 42 | return 301 https://www.example.com/dvorak/$path$is_args$args; 43 | } 44 | 45 | location /notfound/ { 46 | return 404; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /sites.d/www.example.org.conf: -------------------------------------------------------------------------------- 1 | server { 2 | include listen/example.org; 3 | 4 | include include/cloudflare-client-ip; 5 | 6 | server_name 7 | www.example.org 8 | ; 9 | 10 | # Expose our S3 asset buckets and fotomat translation. 11 | include include/assets-base; 12 | 13 | location / { 14 | return 301 https://m.example.org$request_uri; 15 | } 16 | 17 | location /assets/ { 18 | include include/static-assets; 19 | expires 1h; 20 | 21 | proxy_pass http://service2-upstream/assets/; 22 | } 23 | } 24 | --------------------------------------------------------------------------------