### Install and Start NGINX on Windows Source: https://nginx.org/en/docs/windows.html These commands demonstrate how to unpack the NGINX distribution and start the server from the command line on Windows. ```cmd cd c:\ unzip nginx-1.31.1.zip cd nginx-1.31.1 start nginx ``` -------------------------------- ### Project Setup and Dependency Installation Source: https://nginx.org/en/docs/njs/node_modules.html This snippet demonstrates the initial steps for setting up a new project, including creating a directory, generating a license and gitignore file, and initializing a package.json. It also installs the 'browserify' package, a tool used for bundling JavaScript modules. ```bash mkdir my_project && cd my_project npx license choose_your_license_here > LICENSE npx gitignore node cat > package.json < (https://example.com)", "license": "some_license_here", "private": true, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" } } EOF npm init -y npm install browserify ``` -------------------------------- ### Example Nginx Configuration Source: https://nginx.org/en/docs/ngx_core_module.html A basic Nginx configuration demonstrating user, worker processes, error logging, and event handling settings. This serves as a starting point for Nginx setup. ```nginx user www www; worker_processes 2; error_log /var/log/nginx-error.log info; events { use kqueue; worker_connections 2048; } ... ``` -------------------------------- ### Install Prerequisites on Ubuntu Source: https://nginx.org/en/linux_packages.html Installs necessary packages for Nginx installation on Ubuntu. ```bash sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring ``` -------------------------------- ### Example: Simple Nginx Core Module (ngx_foo_module) Source: https://nginx.org/en/docs/dev/development_guide.html A basic example of a core Nginx module demonstrating configuration directives, context, and module definition. ```c /* * Copyright (C) Author. */ #include #include typedef struct { ngx_flag_t enable; } ngx_foo_conf_t; static void *ngx_foo_create_conf(ngx_cycle_t *cycle); static char *ngx_foo_init_conf(ngx_cycle_t *cycle, void *conf); static char *ngx_foo_enable(ngx_conf_t *cf, void *post, void *data); static ngx_conf_post_t ngx_foo_enable_post = { ngx_foo_enable }; static ngx_command_t ngx_foo_commands[] = { { ngx_string("foo_enabled"), NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, 0, offsetof(ngx_foo_conf_t, enable), &ngx_foo_enable_post }, ngx_null_command }; static ngx_core_module_t ngx_foo_module_ctx = { ngx_string("foo"), ngx_foo_create_conf, ngx_foo_init_conf }; ngx_module_t ngx_foo_module = { NGX_MODULE_V1, &ngx_foo_module_ctx, /* module context */ ngx_foo_commands, /* module directives */ NGX_CORE_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ ``` -------------------------------- ### MP4 Pseudo-Streaming URL Examples Source: https://nginx.org/en/docs/http/ngx_http_mp4_module.html Demonstrates how to request MP4 files with specific start and end times for pseudo-streaming. The 'start' argument specifies the beginning playback time in seconds, and the 'end' argument specifies the end time. ```nginx http://example.com/elephants_dream.mp4?start=238.88 ``` ```nginx http://example.com/elephants_dream.mp4?start=238.88&end=555.55 ``` -------------------------------- ### Example Configuration Source: https://nginx.org/en/docs/http/ngx_http_v3_module.html This example shows how to configure Nginx to support HTTP/3, including setting up SSL/TLS and advertising HTTP/3 support via the Alt-Svc header. ```APIDOC ## Example Configuration ```http http { log_format quic '$remote_addr - $remote_user [$time_local] '; '"$request" $status $body_bytes_sent '; '"$http_referer" "$http_user_agent" "$http3"'; access_log logs/access.log quic; server { # for better compatibility it's recommended # to use the same port for http/3 and https listen 8443 quic reuseport; listen 8443 ssl; ssl_certificate certs/example.com.crt; ssl_certificate_key certs/example.com.key; location / { # used to advertise the availability of HTTP/3 add_header Alt-Svc 'h3=":8443"; ma=86400'; } } } ``` ``` -------------------------------- ### SCGI Store Configuration Example Source: https://nginx.org/en/docs/http/ngx_http_scgi_module.html An example configuration demonstrating how to use SCGI storage, including setting the temporary path, access permissions, and mapping to a local directory. ```nginx location /images/ { root /data/www; error_page 404 = /fetch$uri; } location /fetch/ { internal; scgi_pass backend:9000; ... scgi_store on; scgi_store_access user:rw group:rw all:r; scgi_temp_path /data/temp; alias /data/www/; } ``` -------------------------------- ### FastCGI Store Example with Image Fetching Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html This example demonstrates using fastcgi_store to create local copies of static unchangeable files, like images, by fetching them via a FastCGI backend when a 404 error occurs. ```nginx location /images/ { root /data/www; error_page 404 = /fetch$uri; } location /fetch/ { internal; fastcgi_pass backend:9000; ... fastcgi_store on; fastcgi_store_access user:rw group:rw all:r; fastcgi_temp_path /data/temp; alias /data/www/; } ``` -------------------------------- ### Example Mail Configuration Source: https://nginx.org/en/docs/mail/ngx_mail_core_module.html This is an example configuration for the mail module, demonstrating how to set up mail servers for different protocols and authentication methods. Ensure the module is enabled during Nginx compilation. ```nginx worker_processes auto; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } mail { server_name mail.example.com; auth_http localhost:9000/cgi-bin/nginxauth.cgi; imap_capabilities IMAP4rev1 UIDPLUS IDLE LITERAL+ QUOTA; pop3_auth plain apop cram-md5; pop3_capabilities LAST TOP USER PIPELINING UIDL; smtp_auth login plain cram-md5; smtp_capabilities "SIZE 10485760" ENHANCEDSTATUSCODES 8BITMIME DSN; xclient off; server { listen 25; protocol smtp; } server { listen 110; protocol pop3; proxy_pass_error_message on; } server { listen 143; protocol imap; } server { listen 587; protocol smtp; } } ``` -------------------------------- ### Install Alpine Prerequisites Source: https://nginx.org/en/linux_packages.html Installs necessary packages for Nginx installation on Alpine Linux. ```bash sudo apk add openssl curl ca-certificates ``` -------------------------------- ### Example dav_access Directive Source: https://nginx.org/en/docs/http/ngx_http_dav_module.html Configures access permissions for newly created files and directories. This example grants read-write access to the user and group, and read-only access to all. ```nginx dav_access user:rw group:rw all:r; ``` -------------------------------- ### Install protobufjs and Generate Static Code Source: https://nginx.org/en/docs/njs/node_modules.html Install the protobufjs library and use its command-line tool to generate static JavaScript code from a .proto file. This avoids dynamic code generation, which is restricted in njs. ```bash npm install protobufjs npx pbjs -t static-module helloworld.proto > static.js ``` -------------------------------- ### Install Prerequisites on SLES Source: https://nginx.org/en/linux_packages.html Installs necessary packages for Nginx installation on SLES. ```bash sudo zypper install curl ca-certificates gpg2 ``` -------------------------------- ### Example MQTT Configuration Source: https://nginx.org/en/docs/stream/ngx_stream_mqtt_filter_module.html This configuration enables MQTT protocol support and sets client connection parameters. ```nginx listen 127.0.0.1:18883; proxy_pass backend; proxy_buffer_size 16k; mqtt on; mqtt_set_connect clientid "$client"; mqtt_set_connect username "$name"; ``` -------------------------------- ### HLS Playlist Example with Forwarded Arguments Source: https://nginx.org/en/docs/http/ngx_http_hls_module.html An example HLS playlist demonstrating how arguments are appended to fragment URIs when hls_forward_args is enabled. ```plaintext #EXTM3U #EXT-X-VERSION:3 #EXT-X-TARGETDURATION:15 #EXT-X-PLAYLIST-TYPE:VOD #EXTINF:9.333, test.mp4.ts?start=0.000&end=9.333&a=1&b=2 #EXTINF:7.167, test.mp4.ts?start=9.333&end=16.500&a=1&b=2 #EXTINF:5.416, test.mp4.ts?start=16.500&end=21.916&a=1&b=2 #EXTINF:5.500, test.mp4.ts?start=21.916&end=27.416&a=1&b=2 #EXTINF:15.167, test.mp4.ts?start=27.416&end=42.583&a=1&b=2 #EXTINF:9.626, test.mp4.ts?start=42.583&end=52.209&a=1&b=2 #EXT-X-ENDLIST ``` -------------------------------- ### Install Nginx with Dynamic Modules on Alpine Source: https://nginx.org/en/linux_packages.html Installs Nginx along with specified dynamic modules from the Nginx repository on Alpine Linux. ```bash sudo apk add nginx-module-image-filter@nginx nginx-module-njs@nginx ``` -------------------------------- ### Example API Requests Source: https://nginx.org/en/docs/http/ngx_http_api_module.html These examples demonstrate how to access various API endpoints for status information and configuration management, including specific zones and upstream details. ```http http://127.0.0.1/api/9/ http://127.0.0.1/api/9/nginx http://127.0.0.1/api/9/connections http://127.0.0.1/api/9/workers http://127.0.0.1/api/9/http/requests http://127.0.0.1/api/9/http/server_zones/server_backend http://127.0.0.1/api/9/http/caches/cache_backend http://127.0.0.1/api/9/http/upstreams/backend http://127.0.0.1/api/9/http/upstreams/backend/servers/ http://127.0.0.1/api/9/http/upstreams/backend/servers/1 http://127.0.0.1/api/9/http/keyvals/one?key=arg1 http://127.0.0.1/api/9/stream/ http://127.0.0.1/api/9/stream/server_zones/server_backend http://127.0.0.1/api/9/stream/upstreams/ http://127.0.0.1/api/9/stream/upstreams/backend http://127.0.0.1/api/9/stream/upstreams/backend/servers/1 ``` -------------------------------- ### Install nginx on RHEL Source: https://nginx.org/en/linux_packages.html Installs the nginx package from the configured yum repository. You will be prompted to accept the GPG key; verify its fingerprint before accepting. ```bash sudo yum install nginx ``` -------------------------------- ### Internal Rewrite Module Instructions (Example 1) Source: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html Internal instructions generated from the first Nginx rewrite example. This shows the compiled representation of 'if' and 'rewrite' directives. ```text variable $forbidden check against zero return 403 end of code variable $slow check against zero match of regular expression copy "/" copy $1 copy "/mp3/" copy $2 copy ".mp3" end of regular expression end of code ``` -------------------------------- ### Nginx List Iteration Example Source: https://nginx.org/en/docs/dev/development_guide.html Shows how to iterate over items in an Nginx list by accessing its parts and elements directly. ```c ngx_str_t *v; ngx_uint_t i; ngx_list_t *list; ngx_list_part_t *part; /* ... list creation and population ... */ /* iterate over the list */ part = &list->part; v = part->elts; for (i = 0; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; v = part->elts; i = 0; } ngx_do_smth(&v[i]); } ``` -------------------------------- ### Status Request Examples Source: https://nginx.org/en/docs/http/ngx_http_status_module.html These examples show how to make requests to access different types of status information provided by the module, such as general status, Nginx version, cache status, and upstream details. ```http http://127.0.0.1/status http://127.0.0.1/status/nginx_version http://127.0.0.1/status/caches/cache_backend http://127.0.0.1/status/upstreams http://127.0.0.1/status/upstreams/backend http://127.0.0.1/status/upstreams/backend/peers/1 http://127.0.0.1/status/upstreams/backend/peers/1/weight http://127.0.0.1/status/stream http://127.0.0.1/status/stream/upstreams http://127.0.0.1/status/stream/upstreams/backend http://127.0.0.1/status/stream/upstreams/backend/peers/1 http://127.0.0.1/status/stream/upstreams/backend/peers/1/weight ``` -------------------------------- ### Example Stream Configuration Source: https://nginx.org/en/docs/stream/ngx_stream_core_module.html This configuration sets up upstream servers for load balancing and defines stream servers to listen on specific ports and protocols, proxying traffic to the defined upstreams. It includes examples for TCP, UDP, and Unix domain sockets. ```nginx worker_processes auto; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } stream { upstream backend { hash $remote_addr consistent; server backend1.example.com:12345 weight=5; server 127.0.0.1:12345 max_fails=3 fail_timeout=30s; server unix:/tmp/backend3; } upstream dns { server 192.168.0.1:53535; server dns.example.com:53; } server { listen 12345; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass backend; } server { listen 127.0.0.1:53 udp reuseport; proxy_timeout 20s; proxy_pass dns; } server { listen [::1]:12345; proxy_pass unix:/tmp/stream.socket; } } ``` -------------------------------- ### Nginx Variable Get Handler Example Source: https://nginx.org/en/docs/dev/development_guide.html Implements a get handler for an Nginx variable to retrieve the connection number. It allocates memory for the value, formats the number, and sets the appropriate flags for the ngx_http_variable_value_t structure. ```c static ngx_int_t gx_http_variable_connection(ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data) { u_char *p; p = ngx_pnalloc(r->pool, NGX_ATOMIC_T_LEN); if (p == NULL) { return NGX_ERROR; } v->len = ngx_sprintf(p, "%uA", r->connection->number) - p; v->valid = 1; v->no_cacheable = 0; v->not_found = 0; v->data = p; return NGX_OK; } ``` -------------------------------- ### Nginx Example Configuration with Perl Source: https://nginx.org/en/docs/http/ngx_http_perl_module.html Demonstrates setting up Perl modules, requiring a specific module, and defining a Perl handler for a location. Also shows setting a variable using a Perl subroutine. ```nginx http { perl_modules perl/lib; perl_require hello.pm; perl_set $msie6 ' sub { my $r = shift; my $ua = $r->header_in("User-Agent"); return "" if $ua =~ /Opera/; return "1" if $ua =~ / MSIE [6-9]\.\d+/; return ""; } '; server { location / { perl hello::handler; } } } ``` -------------------------------- ### Limit HTTP Methods with Access Control Source: https://nginx.org/en/docs/http/ngx_http_core_module.html Limits allowed HTTP methods within a location. This example allows only GET requests and denies all others. ```nginx limit_except GET { allow 192.168.1.0/32; deny all; } ``` -------------------------------- ### Nginx Process List After HUP Signal Source: https://nginx.org/en/docs/control.html Example output showing Nginx processes after a HUP signal, indicating a worker process is shutting down and new ones are starting. ```bash PID PPID USER %CPU VSZ WCHAN COMMAND 33126 1 root 0.0 1164 pause nginx: master process /usr/local/nginx/sbin/nginx 33129 33126 nobody 0.0 1380 kqread nginx: worker process is shutting down (nginx) 33134 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33135 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) 33136 33126 nobody 0.0 1368 kqread nginx: worker process (nginx) ``` -------------------------------- ### Disable passing request body to proxied server Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html Example configuration to prevent the original request body from being passed to the proxied server, often used with `proxy_method GET`. ```nginx location /x-accel-redirect-here/ { proxy_method GET; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_pass ... } ``` -------------------------------- ### Nginx List Creation and Item Addition Source: https://nginx.org/en/docs/dev/development_guide.html Demonstrates initializing an Nginx list using `ngx_list_create`, adding items with `ngx_list_push`, and setting string values. ```c ngx_str_t *v; ngx_uint_t i; ngx_list_t *list; ngx_list_part_t *part; list = ngx_list_create(pool, 100, sizeof(ngx_str_t)); if (list == NULL) { /* error */ } /* add items to the list */ v = ngx_list_push(list); if (v == NULL) { /* error */ } gx_str_set(v, "foo"); v = ngx_list_push(list); if (v == NULL) { /* error */ } gx_str_set(v, "bar"); ``` -------------------------------- ### MP4 Module Configuration Example Source: https://nginx.org/en/docs/http/ngx_http_mp4_module.html Configures the ngx_http_mp4_module within a location block. This setup enables MP4 pseudo-streaming, sets buffer sizes, and configures rate limiting for streams. ```nginx location /video/ { mp4; mp4_buffer_size 1m; mp4_max_buffer_size 5m; mp4_limit_rate on; mp4_limit_rate_after 30s; } ``` -------------------------------- ### Prepare Build Directories and Libraries Source: https://nginx.org/en/docs/howto_build_on_win32.html Create necessary directories and unpack the source code for PCRE, zlib, and OpenSSL libraries into the 'objs/lib' directory. Ensure these libraries are compatible with your build. ```bash mkdir objs mkdir objs/lib cd objs/lib tar -xzf ../../pcre2-10.39.tar.gz tar -xzf ../../zlib-1.3.1.tar.gz tar -xzf ../../openssl-3.0.14.tar.gz ``` -------------------------------- ### Example Configuration for Session Logging Source: https://nginx.org/en/docs/http/ngx_http_session_log_module.html This configuration sets up a session log zone and directs requests to it based on client address and User-Agent. It demonstrates how to define a log zone and apply it to a specific location. ```nginx session_log_zone /path/to/log format=combined zone=one:1m timeout=30s md5=$binary_remote_addr$http_user_agent; location /media/ { session_log one; } ``` -------------------------------- ### Install Nginx on SLES Source: https://nginx.org/en/linux_packages.html Installs Nginx on SLES using the zypper package manager. ```bash sudo zypper install nginx ``` -------------------------------- ### Example Configuration for Status Module Source: https://nginx.org/en/docs/http/ngx_http_status_module.html This configuration demonstrates how to set up the status module for both HTTP and stream servers, including defining upstreams and zones. ```nginx http { upstream **backend** { **zone** http_backend 64k; server backend1.example.com weight=5; server backend2.example.com; } proxy_cache_path /data/nginx/cache_backend keys_zone=**cache_backend**:10m; server { server_name backend.example.com; location / { proxy_pass http://backend; proxy_cache cache_backend; health_check; } **status_zone server_backend;** } server { listen 127.0.0.1; location /upstream_conf { upstream_conf; } location /status { status; } location = /status.html { } } } stream { upstream **backend** { **zone** stream_backend 64k; server backend1.example.com:12345 weight=5; server backend2.example.com:12345; } server { listen 127.0.0.1:12345; proxy_pass backend; **status_zone server_backend;** health_check; } } ``` -------------------------------- ### Single-line Comment Example Source: https://nginx.org/en/docs/dev/development_guide.html Example of a single-line comment used for specific code explanations. ```c /* find the server configuration for the address:port */ ``` -------------------------------- ### Build a Simple Native Module with QuickJS C API Source: https://nginx.org/en/docs/njs/native_modules.html Example of a C module implementing `js_init_module` to export `add` and `reverseString` functions. Uses QuickJS memory allocation functions for proper memory tracking. ```c #include #define countof(x) (sizeof(x) / sizeof((x)[0])) /* Add two numbers */ static JSValue js_add(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int a, b; if (argc < 2) { return JS_ThrowTypeError(ctx, "expected 2 arguments"); } if (JS_ToInt32(ctx, &a, argv[0]) < 0) { return JS_EXCEPTION; } if (JS_ToInt32(ctx, &b, argv[1]) < 0) { return JS_EXCEPTION; } return JS_NewInt32(ctx, a + b); } /* Reverse a string */ static JSValue js_reverse_string(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char *reversed; size_t i, len; JSValue result; const char *str; if (argc < 1) { return JS_ThrowTypeError(ctx, "expected 1 argument"); } str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) { return JS_EXCEPTION; } reversed = js_malloc(ctx, len + 1); if (!reversed) { JS_FreeCString(ctx, str); return JS_EXCEPTION; } for (i = 0; i < len; i++) { reversed[i] = str[len - 1 - i]; } reversed[len] = '\0'; result = JS_NewString(ctx, reversed); js_free(ctx, reversed); JS_FreeCString(ctx, str); return result; } /* Module function list */ static const JSCFunctionListEntry js_module_funcs[] = { JS_CFUNC_DEF("add", 2, js_add), JS_CFUNC_DEF("reverseString", 1, js_reverse_string), }; /* Module initialization */ static int js_module_init(JSContext *ctx, JSModuleDef *m) { return JS_SetModuleExportList(ctx, m, js_module_funcs, countof(js_module_funcs)); } /* Required entry point */ JSModuleDef * js_init_module(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_module_init); if (!m) { return NULL; } JS_AddModuleExportList(ctx, m, js_module_funcs, countof(js_module_funcs)); return m; } ``` -------------------------------- ### Install Nginx on Alpine Source: https://nginx.org/en/linux_packages.html Installs the Nginx package from the configured Nginx repository on Alpine Linux. ```bash sudo apk add nginx@nginx ``` -------------------------------- ### Stub Status Output Example Source: https://nginx.org/en/docs/http/ngx_http_stub_status_module.html This is an example of the status information that may be displayed by the stub_status directive. ```text Active connections: 291 server accepts handled requests 16630948 16630948 31070465 Reading: 6 Writing: 179 Waiting: 106 ``` -------------------------------- ### Nginx Queue Usage Example Source: https://nginx.org/en/docs/dev/development_guide.html Illustrates creating a custom structure containing an Nginx queue node, initializing a queue, adding an item, and iterating through it. ```c typedef struct { ngx_str_t value; ngx_queue_t queue; } ngx_foo_t; ngx_foo_t *f; ngx_queue_t values, *q; ngx_queue_init(&values); f = ngx_palloc(pool, sizeof(ngx_foo_t)); if (f == NULL) { /* error */ } gx_str_set(&f->value, "foo"); ngx_queue_insert_tail(&values, &f->queue); /* insert more nodes here */ for (q = ngx_queue_head(&values); q != ngx_queue_sentinel(&values); q = ngx_queue_next(q)) { f = ngx_queue_data(q, ngx_foo_t, queue); ngx_do_smth(&f->value); } ``` -------------------------------- ### Protobufjs Output Example Source: https://nginx.org/en/docs/njs/node_modules.html This example shows the expected hexdump output when a protobufjs-generated message is processed by njs. ```bash $ njs ./njs_bundle.js |hexdump -C 00000000 00 00 00 00 0c 0a 0a 54 65 73 74 53 74 72 69 6e 00000010 67 0a 00000012 ``` -------------------------------- ### Example Configuration for Headers Source: https://nginx.org/en/docs/http/ngx_http_headers_module.html Configure Expires and Cache-Control headers. Use 'expires' with various time formats or 'add_header' for custom directives. ```nginx expires 24h; expires modified +24h; expires @24h; expires 0; expires -1; expires epoch; expires $expires; add_header Cache-Control private; ``` -------------------------------- ### Update MP4 STSZ Atom with Start Sample Offset Source: https://nginx.org/download/patch.2012.mp4.txt Updates the MP4 stsz atom buffer by adjusting the position based on the start sample. It also validates that the start sample is within the bounds of the total sample sizes. ```c if (trak->start_sample > trak->sample_sizes_entries) { ngx_log_error(NGX_LOG_ERR, mp4->file.log, 0, ``` -------------------------------- ### Install TypeScript Source: https://nginx.org/en/docs/njs/typescript.html Install the TypeScript compiler globally using npm. This is required to compile TypeScript files into JavaScript. ```bash # npm install -g typescript ``` -------------------------------- ### Example Configuration for Split Clients Source: https://nginx.org/en/docs/http/ngx_http_split_clients_module.html This configuration demonstrates how to use the split_clients directive to create a variable for A/B testing based on the client's remote address. ```nginx http { split_clients "${remote_addr}AAA" $variant { 0.5% .one; 2.0% .two; * ""; } server { location / { index index${variant}.html; ``` -------------------------------- ### Nginx Pool Allocation Example Source: https://nginx.org/en/docs/dev/development_guide.html Demonstrates creating a pool, allocating a string structure, and allocating unaligned memory for a string. Ensure proper error handling for pool and memory allocations. ```c u_char *p; ngx_str_t *s; ngx_pool_t *pool; pool = ngx_create_pool(1024, log); if (pool == NULL) { /* error */ } s = ngx_palloc(pool, sizeof(ngx_str_t)); if (s == NULL) { /* error */ } ngx_str_set(s, "foo"); p = ngx_pnalloc(pool, 3); if (p == NULL) { /* error */ } ngx_memcpy(p, "foo", 3); ``` -------------------------------- ### Nginx Rewrite Rule Example Source: https://nginx.org/download/patch.2022.mp4.txt Implement URL rewriting using Nginx. This example redirects an old URL to a new one. ```nginx server { listen 80; server_name rewrite.example.com; location /old-page { rewrite ^/old-page$ /new-page permanent; } location /new-page { # ... configuration for new page } } ``` -------------------------------- ### Configure Nginx with QuickJS Support Source: https://nginx.org/en/docs/njs/install.html When compiling Nginx, specify the include and library paths for QuickJS using `--with-cc-opt` and `--with-ld-opt` configuration parameters. ```bash ./configure --add-module=_path-to-njs_/nginx \ --with-cc-opt="-I _path-to-quickjs_" \ --with-ld-opt="-L _path-to-quickjs_" ``` -------------------------------- ### Enable Nginx Proxy Cache HEAD to GET Conversion Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html Enables or disables the conversion of 'HEAD' method to 'GET' for caching purposes. ```nginx proxy_cache_convert_head on; ``` -------------------------------- ### Install nginx on Debian Source: https://nginx.org/en/linux_packages.html Updates the apt package list and installs nginx. This command should be run after configuring the nginx apt repository and pinning. ```bash sudo apt update sudo apt install nginx ``` -------------------------------- ### Build QuickJS Library Source: https://nginx.org/en/docs/njs/install.html Clone the QuickJS repository and build the static library `libquickjs.a` with PIC (Position Independent Code) enabled. ```bash git clone https://github.com/bellard/quickjs cd quickjs CFLAGS='-fPIC' make libquickjs.a ``` -------------------------------- ### Basic Listen Directives Source: https://nginx.org/en/docs/stream/ngx_stream_core_module.html Configure the address and port for accepting connections. Wildcards and hostnames are supported. ```nginx listen 127.0.0.1:12345; listen *:12345; listen 12345; # same as *:12345 listen localhost:12345; ``` -------------------------------- ### Create and Populate Nginx Buffer Chain Source: https://nginx.org/en/docs/dev/development_guide.html An example function demonstrating how to create and populate a chain of Nginx buffers. It shows allocation of chain links and buffers, setting buffer properties, and linking them together. ```c ngx_chain_t * ngx_get_my_chain(ngx_pool_t *pool) { ngx_buf_t *b; ngx_chain_t *out, *cl, **ll; /* first buf */ cl = ngx_alloc_chain_link(pool); if (cl == NULL) { /* error */ } b = ngx_calloc_buf(pool); if (b == NULL) { /* error */ } b->start = (u_char *) "foo"; b->pos = b->start; b->end = b->start + 3; b->last = b->end; b->memory = 1; /* read-only memory */ cl->buf = b; out = cl; ll = &cl->next; /* second buf */ cl = ngx_alloc_chain_link(pool); if (cl == NULL) { /* error */ } b = ngx_create_temp_buf(pool, 3); if (b == NULL) { /* error */ } b->last = ngx_cpymem(b->last, "foo", 3); cl->buf = b; cl->next = NULL; *ll = cl; return out; } ``` -------------------------------- ### Install yum-utils on RHEL Source: https://nginx.org/en/linux_packages.html Installs yum-utils, a collection of utilities for managing yum repositories, which is a prerequisite for setting up the nginx repository on RHEL-based systems. ```bash sudo yum install yum-utils ``` -------------------------------- ### Nginx String Formatting Example Source: https://nginx.org/en/docs/dev/development_guide.html Demonstrates using ngx_sprintf to format an unsigned integer into a buffer. Ensure the buffer is large enough for the formatted output. ```c u_char buf[NGX_INT_T_LEN]; size_t len; ngx_uint_t n; /* set n here */ len = ngx_sprintf(buf, "%ui", n) – buf; ``` -------------------------------- ### Example Geo Configuration Source: https://nginx.org/en/docs/stream/ngx_stream_geo_module.html Defines a geo variable that maps IP addresses and networks to specific values. Includes IPv4 and IPv6 examples. ```nginx geo $geo { default 0; 127.0.0.1 2; 192.168.1.0/24 1; 10.1.0.0/16 1; ::1 2; 2001:0db8::/32 1; } ``` -------------------------------- ### Example ngx_http_geoip_module Configuration Source: https://nginx.org/en/docs/http/ngx_http_geoip_module.html This configuration block demonstrates how to set up the geoip_country, geoip_city, geoip_proxy, and geoip_proxy_recursive directives within the http context. Ensure the specified database files (e.g., GeoIP.dat) are accessible by Nginx. ```nginx http { geoip_country GeoIP.dat; geoip_city GeoLiteCity.dat; geoip_proxy 192.168.100.0/24; geoip_proxy 2001:0db8::/32; geoip_proxy_recursive on; ... } ``` -------------------------------- ### Basic `types` directive example Source: https://nginx.org/en/docs/http/ngx_http_core_module.html The `types` directive maps file name extensions to MIME types. This example shows a basic mapping. ```nginx types { text/html html; image/gif gif; image/jpeg jpg; } ``` -------------------------------- ### HLS Module Example Configuration Source: https://nginx.org/en/docs/http/ngx_http_hls_module.html Configure the HLS module to serve MP4/MOV files with specified fragment lengths and buffer sizes. Ensure the 'root' directive points to the directory containing media files. ```nginx location / { hls; hls_fragment 5s; hls_buffers 10 10m; hls_mp4_buffer_size 1m; hls_mp4_max_buffer_size 5m; root /var/video/; } ``` -------------------------------- ### Example SSL Ciphers Configuration Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html An example of specifying a broad range of ciphers, including support for older protocols and specific cipher types. ```nginx ssl_ciphers ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ``` -------------------------------- ### Install prerequisites for nginx on Debian Source: https://nginx.org/en/linux_packages.html Installs necessary packages such as curl, gnupg2, ca-certificates, lsb-release, and debian-archive-keyring, which are required before setting up the nginx apt repository. ```bash sudo apt install curl gnupg2 ca-certificates lsb-release debian-archive-keyring ``` -------------------------------- ### Adding and Initializing a Shared Memory Zone Source: https://nginx.org/en/docs/dev/development_guide.html Demonstrates how to add a new shared memory zone and register an initialization callback. This is typically done during Nginx configuration parsing. ```c ngx_str_t name; ngx_foo_ctx_t *ctx; ngx_shm_zone_t *shm_zone; ngx_str_set(&name, "foo"); /* allocate shared zone context */ ctx = ngx_pcalloc(cf->pool, sizeof(ngx_foo_ctx_t)); if (ctx == NULL) { /* error */ } /* add an entry for 64k shared zone */ shm_zone = ngx_shared_memory_add(cf, &name, 65536, &ngx_foo_module); if (shm_zone == NULL) { /* error */ } /* register init callback and context */ shm_zone->init = ngx_foo_init_zone; shm_zone->data = ctx; ... ``` ```c static ngx_int_t ngx_foo_init_zone(ngx_shm_zone_t *shm_zone, void *data) { ngx_foo_ctx_t *octx = data; size_t len; ngx_foo_ctx_t *ctx; ngx_slab_pool_t *shpool; value = shm_zone->data; if (octx) { /* reusing a shared zone from old cycle */ ctx->value = octx->value; return NGX_OK; } shpool = (ngx_slab_pool_t *) shm_zone->shm.addr; if (shm_zone->shm.exists) { /* initialize shared zone context in Windows nginx worker */ ctx->value = shpool->data; return NGX_OK; } /* initialize shared zone */ ctx->value = ngx_slab_alloc(shpool, sizeof(ngx_uint_t)); if (ctx->value == NULL) { return NGX_ERROR; } shpool->data = ctx->value; return NGX_OK; } ``` -------------------------------- ### Handle SSL Renegotiation Start Source: https://nginx.org/download/patch.cve-2009-3555.txt This callback function is invoked during SSL handshake events. It detects the start of a handshake and sets a flag if renegotiation is detected. ```c static void ngx_ssl_info_callback(const ngx_ssl_conn_t *ssl_conn, int where, int ret) { ngx_connection_t *c; if (where & SSL_CB_HANDSHAKE_START) { c = ngx_ssl_get_connection((ngx_ssl_conn_t *) ssl_conn); if (c->ssl->handshaked) { c->ssl->renegotiation = 1; ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, 0, "SSL renegotiation"); } } } ``` -------------------------------- ### Example Stream Configuration Source: https://nginx.org/en/docs/stream/ngx_stream_split_clients_module.html This configuration demonstrates how to use the split_clients directive within a stream block to direct traffic to different upstream groups based on client characteristics. ```nginx stream { ... split_clients "${remote_addr}AAA" $upstream { 0.5% feature_test1; 2.0% feature_test2; * production; } server { ... proxy_pass $upstream; } } ``` -------------------------------- ### Install Node Packages for DNS Packet Handling Source: https://nginx.org/en/docs/njs/node_modules.html Installs necessary npm packages for handling DNS packets, including Babel for transpilation and Webpack for bundling. ```bash $ npm install @babel/core @babel/cli @babel/preset-env babel-loader $ npm install webpack webpack-cli $ npm install buffer $ npm install dns-packet ``` -------------------------------- ### Example Configuration: Stream to HTTP Source: https://nginx.org/en/docs/stream/ngx_stream_pass_module.html This configuration demonstrates passing a connection from the stream module (after SSL termination) to an HTTP server. Ensure the http block is configured to listen on the specified port. ```nginx http { server { listen 8000; location / { root html; } } } stream { server { listen 12345 ssl; ssl_certificate domain.crt; ssl_certificate_key domain.key; pass 127.0.0.1:8000; } } ``` -------------------------------- ### Initialize Hash Table Settings Source: https://nginx.org/en/docs/dev/development_guide.html Configure hash table parameters like max size, bucket size, and pool for optimal performance. The `key` function determines how hash keys are generated. ```c ngx_hash_t foo_hash; ngx_hash_init_t hash; hash.hash = &foo_hash; hash.key = ngx_hash_key; hash.max_size = 512; hash.bucket_size = ngx_align(64, ngx_cacheline_size); hash.name = "foo_hash"; hash.pool = cf->pool; hash.temp_pool = cf->temp_pool; ``` -------------------------------- ### Example Configuration for Limit Connections Source: https://nginx.org/en/docs/http/ngx_http_limit_conn_module.html This configuration sets up a shared memory zone 'addr' for tracking connections based on client IP addresses and applies a limit of 1 connection per IP to the '/download/' location. ```nginx http { limit_conn_zone $binary_remote_addr zone=addr:10m; ... server { ... location /download/ { limit_conn addr 1; } ``` -------------------------------- ### Start Nginx Debug Binary on Linux Source: https://nginx.org/en/docs/debugging_log.html On Linux, use the `nginx-debug` binary for debugging logs. Stop the regular Nginx service before starting the debug version. ```bash service nginx stop service nginx-debug start ``` -------------------------------- ### Example Configuration for ngx_http_keyval_module Source: https://nginx.org/en/docs/http/ngx_http_keyval_module.html This configuration sets up a key-value zone and a variable that retrieves values from it. It also defines API access for managing the key-value pairs. ```nginx http { keyval_zone zone=one:32k state=/var/lib/nginx/state/one.keyval; keyval $arg_text $text zone=one; ... server { ... location / { return 200 $text; } location /api { api write=on; } } } ``` -------------------------------- ### Example Configuration for set directive Source: https://nginx.org/en/docs/stream/ngx_stream_set_module.html This example demonstrates how to use the `set` directive to assign a value to a variable within a server block. The variable `$true` is set to `1`. ```nginx server { listen 12345; set $true 1; } ``` -------------------------------- ### Example Configuration for Charset Module Source: https://nginx.org/en/docs/http/ngx_http_charset_module.html Includes a charset map and sets the charset and source_charset directives. This configuration enables character set conversion. ```nginx include conf/koi-win; charset windows-1251; source_charset koi8-r; ```