{"id":21989335,"url":"https://github.com/izzypt/nginx_demo","last_synced_at":"2026-05-02T01:33:00.876Z","repository":{"id":263840470,"uuid":"891479741","full_name":"izzypt/NGINX_demo","owner":"izzypt","description":"A short demo project on the basic use cases for NGINX","archived":false,"fork":false,"pushed_at":"2025-01-03T13:25:34.000Z","size":13056,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-28T08:52:37.588Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/izzypt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-20T12:11:08.000Z","updated_at":"2025-01-03T13:25:37.000Z","dependencies_parsed_at":"2024-11-20T15:49:49.935Z","dependency_job_id":null,"html_url":"https://github.com/izzypt/NGINX_demo","commit_stats":null,"previous_names":["izzypt/nginx_demo"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izzypt%2FNGINX_demo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izzypt%2FNGINX_demo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izzypt%2FNGINX_demo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izzypt%2FNGINX_demo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/izzypt","download_url":"https://codeload.github.com/izzypt/NGINX_demo/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245048282,"owners_count":20552483,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-29T19:28:59.954Z","updated_at":"2026-05-02T01:33:00.862Z","avatar_url":"https://github.com/izzypt.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NGINX\n\n# commands\n\n- [nginx -T](#nginx-t) - tests your Nginx configuration for errors and then shows you the complete, merged configuration it would actually use - a \"configuration check and preview\" command .\n\n\n\u003ca id=\"nginx-t\"\u003e\u003c/a\u003e\n### nginx -T\n\n`nginx -T` performs two key actions:\n\n1.  **Configuration Syntax and Logic Validation:** It parses your main `nginx.conf` and all included configuration files, checking for syntactical correctness (e.g., proper use of directives, semicolons, block structures) and basic logical consistency. This includes verifying file paths in directives like `include`, `root`, `access_log`, and `error_log`. If any errors are detected during this parsing phase, Nginx will output specific error messages indicating the file and line number of the issue, and the command will exit with a non-zero status code.\n\n2.  **Full Configuration Tree Output:** If the initial validation passes, `nginx -T` proceeds to process the entire configuration. This involves resolving `include` directives, applying default values to unspecified parameters, and effectively merging all the configuration snippets into a single, coherent configuration structure that Nginx would load into memory. The command then outputs this complete, flattened configuration to the standard output. This output reflects the final state of all directives and their values as they would be applied by the Nginx worker processes.\n\nEssentially, `nginx -T` simulates the initial stages of Nginx startup, specifically the configuration loading and parsing phase. It allows administrators to inspect the final, consolidated configuration without actually starting or reloading the Nginx service, thus preventing potential service disruptions due to configuration errors. The output is a direct representation of Nginx's internal configuration tree.\n\n**Scenario 1: Valid Configuration**\n\nLet's say you have a basic `nginx.conf` and a site configuration in `sites-enabled/mysite.conf`. If both files have correct syntax, running `nginx -T` might produce output like this (the actual configuration will be much longer):\n\n```\nnginx: the configuration file /etc/nginx/nginx.conf syntax is ok\nnginx: configuration file /etc/nginx/nginx.conf test is successful\n# configuration file /etc/nginx/nginx.conf:\nuser www-data;\nworker_processes auto;\npid /run/nginx.pid;\ninclude /etc/nginx/modules-enabled/*.conf;\n\nhttp {\n    include /etc/nginx/mime.types;\n    default_type application/octet-stream;\n    access_log /var/log/nginx/access.log combined;\n    error_log /var/log/nginx/error.log;\n    sendfile on;\n    tcp_nopush on;\n    tcp_nodelay on;\n    keepalive_timeout 65;\n    types_hash_max_size 2048;\n    include /etc/nginx/conf.d/*.conf;\n    include /etc/nginx/sites-enabled/*; # Here's where mysite.conf gets included\n}\n\n# configuration file /etc/nginx/sites-enabled/mysite.conf:\nserver {\n    listen 80;\n    server_name example.com www.example.com;\n    root /var/www/example.com;\n    index index.html index.htm;\n\n    location / {\n        try_files $uri $uri/ =404;\n    }\n}\n```\n\nThe key here is the initial \"syntax is ok\" and \"test is successful\" messages, followed by the complete, merged configuration. Notice how the contents of `/etc/nginx/sites-enabled/mysite.conf` are included within the `http` block in the final output.\n\n**Scenario 2: Syntax Error**\n\nImagine you accidentally forget a semicolon in your `sites-enabled/mysite.conf`:\n\n```nginx\nserver {\n    listen 80\n    server_name example.com www.example.com;\n    root /var/www/example.com;\n    index index.html index.htm;\n\n    location / {\n        try_files $uri $uri/ =404;\n    }\n}\n```\n\nRunning `nginx -T` would now output an error message:\n\n```\nnginx: [emerg] directive \"listen\" has no arguments in /etc/nginx/sites-enabled/mysite.conf:2\nnginx: configuration file /etc/nginx/nginx.conf test failed\n```\n\nThis clearly points out the error: the `listen` directive on line 2 of `/etc/nginx/sites-enabled/mysite.conf` is missing its port number argument and the required semicolon. The \"test failed\" message indicates that Nginx would refuse to load this configuration.\n\n**Scenario 3: Invalid File Path**\n\nSuppose you have a typo in the `access_log` directive in your main `nginx.conf`:\n\n```nginx\nhttp {\n    # ... other directives ...\n    access_log /var/log/nginx/accsss.log combined; # Typo here\n    # ...\n}\n```\n\nRunning `nginx -T` might still show \"syntax is ok\" because the directive itself is syntactically correct. However, when Nginx tries to apply this configuration, it might encounter issues. While `-T` primarily focuses on syntax and basic logic, it might not always catch all runtime errors related to invalid paths. However, it's still valuable for catching the more obvious configuration mistakes.\n\n**Key Takeaway from Examples:**\n\n* `nginx -T` helps you see the final, combined configuration.\n* It's excellent for catching syntax errors that would prevent Nginx from starting or reloading.\n* The error messages are usually quite informative, pointing to the specific file and line number with the problem.\n\nBy using `nginx -T` regularly, especially after making configuration changes, you can significantly reduce the risk of unexpected downtime and make debugging much easier.\n\n---\n\nOther cool articles:\n\n- https://medium.com/@ksaquib/nginx-zero-to-hero-your-ultimate-guide-from-beginner-to-advanced-mastery-57e2dad6a77a\n\n---\n\n### NGINX as a webserver.\n\nBack in the day, when the internet was still simple, with less users, the basic use case was:\n\n- a browser requestes a web page from a web server (web server refers to both the physical machine and software running on the machine)\n\n- The web server assembled the page and send it back to the browser, which then displays it to the user.\n\nNGINX would be this server software that responds to client HTTP requests.\n\n![NGINX web server](images/image.png)\n\n### NGINX as a a proxy server.\n\n![nginx_proxy_functionalities](images/image-8.png)\n\nWhen web became popular, we have thousands or millions of requests per website. Imagine one single server handling millions of requests...\n\n![millions-of-requests](images/image-1.png)\n\nWe need a few more servers to handle the load, so we add 10 NGINX webservers..\n\nBut now we need something that determines where requests from the browser end. Which one of those 10 servers will handle them.\n\nThis is where load balancing comes in.. We can use another NGINX as a load balances that proxies the requests to those 10 servers.\n\n(proxy = \"acting on behalf of another\")\n(proxy server = \"intermediary server that forwards client requests to other servers\")\n\n\n![NGINX_load_balancing](images/image-2.png)\n\nThe load is distributed based on whichever algorithm was defined on it. Some examples are:\n\n- lest connections (routes traffic to the server with the fewest active connections)\n- round robin (distributes client requests in a sequential, cyclical manner to each server in the group)\n\n### Loadbalancing is just one functionality of a proxy server. Let's look at caching now\n\nImagine that a New York Times article comes out and million of people open it. The normal flow would be:\n\n- Every time a request landed with one of the web servers, it would assemble the response (put images together, get them from database, add all links, etc..) and it would happen millions of times for each request. \n\n![caching NGINX](images/image-3.png)\n\nThat seems pretty inneficient. Caching allow us to do the heavy lifting only once (get all the data from db, put the text together, images, etc..) and store the response.\n\n![proxy_cache](images/image-4.png)\n\n![caching](images/image-5.png)\n\n### A single entrypoint\n\nImagine we have 100's of servers of an online banking app or a social network like facebook. \n\nThat makes those servers a pretty juicy target for hackers, like personal data, banking data, etc...\n\n\nImagine you exposed all 100's servers to public access... all those requests would be able to directly hit each of the web servers...\n\n![one_entrypoint](images/image-6.png)\n\nWe want to reduce the risk by providing only one server that is publicly acessible. We can put all our security efforts into one server instead of 100's.\n\nHaving only one entrypoint (the proxy) as publicly acessible reduces the secuirty attack surface tremendously and acts like a shield or security layer.\n\n![proxy_entrypoin](images/image-7.png)\n\n### Encrypted communications\n\n![encrypted_ssl](images/image-9.png)\n\nOne very important security measure is encrypted communication.\n\n- NGINX can handle SSL/TLS encryption and decryption\n\nThe browser will send encrypted message to the proxy - which means, even if attacker intercepts message, they can't read it - only the proxy server can decrypt it or for added security (when proxy acts as shield) it will pass that encrypted message into the web servers.\n\nWe can configure the proxy to deny any requests that is not encrypted and only accept encrypted requests.\n\n![encrypted_communication](images/image-10.png)\n\n### Compression\n\nNow, imagine NetFlix - which , by the way , uses NGINX on it's backend - has millions of users and millions of requests for videos on it's webservers.\n\n![Netflix_nginx](images/image-11.png)\n\nMillions of requests are sent for a high quality video to NetFlix. Imagine if NGINX proxy server would have to send back the entire high bquality video to millions of users at once (that's a lot of bandwidth - imagine how long it would take) and that's where compressions helps.\n\n![nginx_compression](images/image-12.png)\n\nNGINX proxy can also BE CONFIGURED TO COMPRESS LARGE IMAGES OR VIDEO FILES TO SAVE BANDWIDTH , BOTH ON THE receiving end and on the server side.\n\nIt also support chuncking (segmentation - sending response in chuncks)\n\n![chuncking_nginx](images/image-13.png)\n\n\n# How to setup NGINX\n\nUsing NGINX configuration\n\n![nginx.conf](images/image-14.png)\n\nHere you define wether you want your NGINX to act as a web server or a proxy server by configuring where it should forward the traffic to or if it should handle it itself. \n\n![nginx_configuration_file](images/image-15.png)\n\n![location_directive_nginx](images/image-16.png)\n\n\nHere, we redirect all traffic received in port 80 (http) to 443 (https) and we serve content over SSL/TLS (configured):\n\n\u003cimg width=\"896\" alt=\"image\" src=\"https://github.com/user-attachments/assets/19e9fac0-7695-4b0d-9d7e-263910f804bf\"\u003e\n\n\nOn the next image, we configure load balancing to multiple backend servers and within that configuration you can define which load balancing algo to use..\n\n\u003cimg width=\"1117\" alt=\"image\" src=\"https://github.com/user-attachments/assets/87c48ff1-b185-4e0c-80c3-0c0a3784f902\"\u003e\n\nOn the next one, you can see the caching configuration example:\n\n\u003cimg width=\"1675\" alt=\"image\" src=\"https://github.com/user-attachments/assets/b271aa3a-90e7-414e-8792-222dcbb8ccf9\"\u003e\n\nYou can see the full list of all configuration blocks and directives here:\n\nhttps://nginx.org/en/docs/\n\n### NGINX in Kubernetes - NGINX as k8'S ingress controller\n\n\u003cimg width=\"1660\" alt=\"image\" src=\"https://github.com/user-attachments/assets/4ae1444b-0a0f-448c-82fb-aa6cd81c8968\"\u003e\n\n\u003cimg width=\"1615\" alt=\"image\" src=\"https://github.com/user-attachments/assets/90b072d2-80c1-48fd-ab54-a766d6e14f6f\"\u003e\n\n\nNGINX ingress controller is used inside the cluster, so unlike the proxy for web servers it is not publicly acessible, so you can't acess the NGINX ingress controller from the browser, it lives inside the cluster.\n\n\u003cimg width=\"1592\" alt=\"image\" src=\"https://github.com/user-attachments/assets/643a5c91-431d-4276-acca-8d1a4fb0aee3\"\u003e\n\n\nWho gets the request from public ? It's the cloud load balancer. \n\nThis is important because it adds a security layer to those requests. so, the cluster component is never directly exposed to public access.\n\nThe ELB (aws load balancer), forwards to the ingress controller within the cluster, which then routes the traffic based on intelligent logic to different applications within the cluster.\n\n\u003cimg width=\"1213\" alt=\"image\" src=\"https://github.com/user-attachments/assets/99f284eb-c89c-4915-96e5-b25dba96111d\"\u003e\n\n# NGINX configuration file (nginx.conf)\n\nThe `nginx.conf` file is the main configuration file for **NGINX**, controlling how it handles requests, serves content, and communicates with clients. Here's a brief overview:\n\n---\n\n### **Structure of `nginx.conf`**\nThe file is organized into **directives** and **blocks**, structured hierarchically:\n\n1. **Main Context**: \n   - Global settings that affect the entire NGINX instance.\n   - Example: Worker processes, logging paths, and file locations.\n   - Example:\n     ```nginx\n     worker_processes 4;\n     error_log /var/log/nginx/error.log;\n     ```\n\n2. **Events Context**:\n   - Handles connection-related settings.\n   - Example:\n     ```nginx\n     events {\n         worker_connections 1024;\n     }\n     ```\n\n3. **HTTP Context**:\n   - Configures web server behavior, including serving HTTP content and reverse proxying.\n   - Contains nested blocks:\n     - **Server Block**: Defines server-specific settings like domains and ports.\n     - **Location Block**: Defines URL-specific settings.\n   - Example:\n     ```nginx\n     http {\n         include /etc/nginx/mime.types;\n         server {\n             listen 80;\n             server_name example.com;\n\n             location / {\n                 root /var/www/html;\n                 index index.html;\n             }\n         }\n     }\n     ```\n\n4. **Stream Context** (optional):\n   - Handles TCP/UDP proxying (for non-HTTP traffic).\n   - Example:\n     ```nginx\n     stream {\n         server {\n             listen 12345;\n             proxy_pass backend:12345;\n         }\n     }\n     ```\n\n---\n\n### **Key Directives**\n1. **Worker Processes**:\n   - `worker_processes`: Number of worker processes for handling requests.\n\n2. **Server and Port**:\n   - `server_name`: Defines the domain(s) the server responds to.\n   - `listen`: Specifies the port (e.g., `80` for HTTP, `443` for HTTPS).\n\n3. **Root and Index**:\n   - `root`: Specifies the document root.\n   - `index`: Defines the default file (e.g., `index.html`) for requests.\n\n4. **Reverse Proxy**:\n   - `proxy_pass`: Forwards client requests to another server (backend).\n   - Example:\n     ```nginx\n     location /api/ {\n         proxy_pass http://backend_server;\n     }\n     ```\n\n5. **Logging**:\n   - `access_log`: Logs access requests.\n   - `error_log`: Logs errors.\n\n---\n\n### **What’s Most Important About `nginx.conf`**\n1. **Modularity**:\n   - It can include other configuration files, typically stored in `/etc/nginx/conf.d/` or `/etc/nginx/sites-enabled/`.\n\n2. **Flexibility**:\n   - Can handle multiple domains (virtual hosts) and URL-specific rules.\n\n3. **Optimization**:\n   - Configure caching, gzip compression, and worker connections for performance.\n\n4. **Security**:\n   - Supports HTTPS, rate limiting, and access control.\n\n5. **Error Handling**:\n   - Custom error pages can be defined for specific status codes.\n\nBy understanding and correctly configuring `nginx.conf`, you can tailor NGINX to meet the needs of your application efficiently and securely.\n\n![image](https://github.com/user-attachments/assets/f7b292a6-b699-4304-8ac8-05c5242c63ee)\n\n![image](https://github.com/user-attachments/assets/6b8ac71b-a0b3-46df-b28d-05892b7caf9c)\n\n![image](https://github.com/user-attachments/assets/6d97ad53-2b33-4b9a-a861-63b9a4a6b6cf)\n\n![image](https://github.com/user-attachments/assets/47550d00-13f7-4dfb-a283-6abd7d627603)\n\n![image](https://github.com/user-attachments/assets/82b91341-16b0-4e5b-9997-35c3aa8fe112)\n\n![image](https://github.com/user-attachments/assets/8ae9c98e-f3ec-406b-8e09-23919b2c2937)\n\n![image](https://github.com/user-attachments/assets/93a74c95-d33e-485f-9921-8026e8611c15)\n\n![image](https://github.com/user-attachments/assets/ee46bae1-9f99-4593-93a9-d623be3ca94d)\n\n\n\n# Enabling SSL/TLS encryption\n\n1- Obtain an SSL/TLS certificate\n\n![image](https://github.com/user-attachments/assets/b3222492-b512-44ff-a935-98bf80e96fc5)\n\nThe certificate validates the server and contains a punlic key that client can use to talk to the server.\n\nWays of generating certificate:\n\n1 - A self-signed certificate\n  - Generated and signed by the server itself.\n  - Useful for testing or internal sites, but not recommended for production.\n\n2 - CA signed certificate\n  - Issued and authenticated by a trsuted certificate authority.\n  - CA verifies the identity of the organization requesting the certificate.\n\n![image](https://github.com/user-attachments/assets/98537ab8-68b5-4298-929c-85f0e312c575)\n\n\n![image](https://github.com/user-attachments/assets/2536810a-55dc-4542-b3b6-9ceac47ebcad)\n\n![image](https://github.com/user-attachments/assets/ae088b2f-2655-4201-a949-6c7e7b708eb5)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fizzypt%2Fnginx_demo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fizzypt%2Fnginx_demo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fizzypt%2Fnginx_demo/lists"}