{"id":3523,"date":"2025-12-27T19:46:41","date_gmt":"2025-12-27T16:46:41","guid":{"rendered":"https:\/\/www.dchost.com\/blog\/nginx-reverse-proxy-and-simple-load-balancer-setup-for-small-projects\/"},"modified":"2026-11-04T19:54:11","modified_gmt":"2026-11-04T16:54:11","slug":"nginx-reverse-proxy-load-balancer-small-projects","status":"publish","type":"post","link":"https:\/\/www.dchost.com\/blog\/en\/nginx-reverse-proxy-load-balancer-small-projects\/","title":{"rendered":"Nginx Reverse Proxy and Load Balancer for Small Projects"},"content":{"rendered":"<div class=\"dchost-blog-content-wrapper\"><p>For many small projects, the first deployment runs on a single <a href=\"https:\/\/www.dchost.com\/vps\">VPS<\/a>: web server, application, and database all on one machine. It works well at the start, but as traffic grows or you add more services (API, admin panel, background workers), things become harder to manage. <a href=\"https:\/\/www.dchost.com\/ssl\">SSL certificate<\/a>s are scattered, firewall rules get complex, and you have no easy way to add a second application server when you need more capacity. This is exactly where a lightweight Nginx reverse proxy and simple load balancer architecture solves real, everyday problems without forcing you into heavyweight, enterprise-style setups.<\/p>\n<p>In this guide, we will walk through a practical, step-by-step Nginx configuration for small SaaS apps, WooCommerce stores, landing pages, or internal tools. We will keep the design intentionally simple: one front-facing Nginx reverse proxy and one or more backend application servers. You will learn why this pattern works so well for small projects, how to configure it on a VPS, and how to extend it into a basic load balancer when you need more performance or backend redundancy.<\/p>\n<div id=\"toc_container\" role=\"navigation\" aria-label=\"Table of Contents\" data-nosnippet class=\"toc_transparent no_bullets toc_numbered toc_title_center\"><p class=\"toc_title\">\u0130\u00e7indekiler<\/p><ul class=\"toc_list\"><li><a href=\"#What_an_Nginx_Reverse_Proxy_and_Load_Balancer_Actually_Do_for_You\"><span class=\"toc_number toc_depth_1\">1.<\/span> What an Nginx Reverse Proxy and Load Balancer Actually Do for You<\/a><\/li><li><a href=\"#Reference_Architecture_for_Small_Projects\"><span class=\"toc_number toc_depth_1\">2.<\/span> Reference Architecture for Small Projects<\/a><\/li><li><a href=\"#Preparing_Your_Servers_OS_Security_and_DNS\"><span class=\"toc_number toc_depth_1\">3.<\/span> Preparing Your Servers: OS, Security and DNS<\/a><ul><li><a href=\"#1_Provision_your_servers\"><span class=\"toc_number toc_depth_2\">3.1.<\/span> 1. Provision your servers<\/a><\/li><li><a href=\"#2_Secure_the_basics_on_each_VPS\"><span class=\"toc_number toc_depth_2\">3.2.<\/span> 2. Secure the basics on each VPS<\/a><\/li><li><a href=\"#3_Configure_DNS\"><span class=\"toc_number toc_depth_2\">3.3.<\/span> 3. Configure DNS<\/a><\/li><\/ul><\/li><li><a href=\"#StepbyStep_Nginx_as_a_Reverse_Proxy_to_a_Single_Backend\"><span class=\"toc_number toc_depth_1\">4.<\/span> Step\u2011by\u2011Step: Nginx as a Reverse Proxy to a Single Backend<\/a><ul><li><a href=\"#1_Install_Nginx_on_the_front_VPS\"><span class=\"toc_number toc_depth_2\">4.1.<\/span> 1. Install Nginx on the front VPS<\/a><\/li><li><a href=\"#2_Define_your_backend_upstream\"><span class=\"toc_number toc_depth_2\">4.2.<\/span> 2. Define your backend upstream<\/a><\/li><li><a href=\"#3_Create_the_reverse_proxy_server_block\"><span class=\"toc_number toc_depth_2\">4.3.<\/span> 3. Create the reverse proxy server block<\/a><\/li><li><a href=\"#4_Obtain_a_free_Lets_Encrypt_SSL_certificate\"><span class=\"toc_number toc_depth_2\">4.4.<\/span> 4. Obtain a free Let\u2019s Encrypt SSL certificate<\/a><\/li><li><a href=\"#5_Configure_the_backend_application_to_trust_proxy_headers\"><span class=\"toc_number toc_depth_2\">4.5.<\/span> 5. Configure the backend application to trust proxy headers<\/a><\/li><\/ul><\/li><li><a href=\"#Turning_the_Reverse_Proxy_into_a_Simple_Load_Balancer\"><span class=\"toc_number toc_depth_1\">5.<\/span> Turning the Reverse Proxy into a Simple Load Balancer<\/a><ul><li><a href=\"#1_Add_multiple_backend_servers_to_the_upstream\"><span class=\"toc_number toc_depth_2\">5.1.<\/span> 1. Add multiple backend servers to the upstream<\/a><\/li><li><a href=\"#2_Optional_Choose_a_different_load_balancing_method\"><span class=\"toc_number toc_depth_2\">5.2.<\/span> 2. Optional: Choose a different load balancing method<\/a><\/li><li><a href=\"#3_Reload_Nginx_and_verify\"><span class=\"toc_number toc_depth_2\">5.3.<\/span> 3. Reload Nginx and verify<\/a><\/li><li><a href=\"#4_Dealing_with_sticky_sessions_login_carts_etc\"><span class=\"toc_number toc_depth_2\">5.4.<\/span> 4. Dealing with sticky sessions (login, carts, etc.)<\/a><\/li><\/ul><\/li><li><a href=\"#Routing_Multiple_Apps_Behind_One_Nginx_Reverse_Proxy\"><span class=\"toc_number toc_depth_1\">6.<\/span> Routing Multiple Apps Behind One Nginx Reverse Proxy<\/a><ul><li><a href=\"#1_Path-based_routing\"><span class=\"toc_number toc_depth_2\">6.1.<\/span> 1. Path-based routing<\/a><\/li><li><a href=\"#2_Hostname-based_routing\"><span class=\"toc_number toc_depth_2\">6.2.<\/span> 2. Hostname-based routing<\/a><\/li><\/ul><\/li><li><a href=\"#Performance_Tuning_Timeouts_Caching_and_Logs\"><span class=\"toc_number toc_depth_1\">7.<\/span> Performance Tuning: Timeouts, Caching and Logs<\/a><ul><li><a href=\"#1_Reasonable_timeouts\"><span class=\"toc_number toc_depth_2\">7.1.<\/span> 1. Reasonable timeouts<\/a><\/li><li><a href=\"#2_Microcaching_for_dynamic_sites\"><span class=\"toc_number toc_depth_2\">7.2.<\/span> 2. Microcaching for dynamic sites<\/a><\/li><li><a href=\"#3_Logging_and_observability\"><span class=\"toc_number toc_depth_2\">7.3.<\/span> 3. Logging and observability<\/a><\/li><\/ul><\/li><li><a href=\"#Hosting_Different_Stacks_Behind_Nginx\"><span class=\"toc_number toc_depth_1\">8.<\/span> Hosting Different Stacks Behind Nginx<\/a><\/li><li><a href=\"#When_to_Evolve_Beyond_This_Simple_Architecture\"><span class=\"toc_number toc_depth_1\">9.<\/span> When to Evolve Beyond This Simple Architecture<\/a><\/li><li><a href=\"#Summary_and_How_dchostcom_Fits_In\"><span class=\"toc_number toc_depth_1\">10.<\/span> Summary and How dchost.com Fits In<\/a><\/li><\/ul><\/div>\n<h2><span id=\"What_an_Nginx_Reverse_Proxy_and_Load_Balancer_Actually_Do_for_You\">What an Nginx Reverse Proxy and Load Balancer Actually Do for You<\/span><\/h2>\n<p>Before touching any configuration files, it helps to be very clear about what role Nginx will play in this architecture. On your front server, Nginx will act as:<\/p>\n<ul>\n<li><strong>Reverse proxy:<\/strong> Accepts HTTP\/HTTPS requests from the internet and forwards them to one or more internal application servers.<\/li>\n<li><strong>SSL terminator:<\/strong> Handles TLS\/SSL certificates, so backends can speak plain HTTP on a private network.<\/li>\n<li><strong>Router:<\/strong> Sends different paths or hostnames to different backends (e.g. \/api to one server, \/app to another).<\/li>\n<li><strong>Simple load balancer:<\/strong> Distributes requests across multiple backend servers using built-in algorithms.<\/li>\n<\/ul>\n<p>This architecture gives you several concrete benefits:<\/p>\n<ul>\n<li><strong>Centralised SSL management:<\/strong> You only manage certificates on the front Nginx server, instead of repeating the work on each app box.<\/li>\n<li><strong>Cleaner deployments:<\/strong> You can upgrade or replace backend servers without changing public DNS or touching client-side configs.<\/li>\n<li><strong>Easier scaling:<\/strong> When CPU or RAM becomes tight, you can add a second backend and let Nginx distribute the load.<\/li>\n<li><strong>Better separation of concerns:<\/strong> The front server focuses on HTTP, security headers, and caching; backend servers focus on PHP, Node.js, or other application runtimes.<\/li>\n<\/ul>\n<p>If you are already using Nginx directly on a single VPS for your app, this guide adds a dedicated front proxy. Keep an HTTP-speaking service on each backend; moving the public-facing layer does not replace backend web-server or application-runtime configuration.<\/p>\n<h2><span id=\"Reference_Architecture_for_Small_Projects\">Reference Architecture for Small Projects<\/span><\/h2>\n<p>Let\u2019s define a concrete, minimal architecture we\u2019ll build in this article.<\/p>\n<ul>\n<li><strong>Front VPS:<\/strong> Public-facing Nginx reverse proxy and load balancer. Has a public IP and DNS A\/AAAA records for your domain. Handles SSL. This single front server remains a single point of failure.<\/li>\n<li><strong>Backend VPS #1:<\/strong> Runs your main application behind an HTTP endpoint (e.g. a web server in front of PHP-FPM, or an HTTP application server for Node.js, Python, or Ruby). Accessible from the front VPS over a private network or firewall-restricted public IP.<\/li>\n<li><strong>Optional Backend VPS #2:<\/strong> Identical or similar app server to share load or act as failover.<\/li>\n<li><strong>Database server:<\/strong> May live on Backend #1 for very small setups, or on a separate VPS\/<a href=\"https:\/\/www.dchost.com\/dedicated-server\">dedicated server<\/a> when you grow.<\/li>\n<\/ul>\n<p>This pattern can be useful for:<\/p>\n<ul>\n<li>New SaaS products that need a path to add application servers as they grow.<\/li>\n<li>WooCommerce or custom e\u2011commerce sites preparing for future traffic spikes.<\/li>\n<li>Internal dashboards and APIs where you want to isolate public traffic from the app machines.<\/li>\n<\/ul>\n<p>If you are still at the \u201cone VPS for everything\u201d stage, you can apply the same concepts on a single machine (Nginx reverse proxy in front of multiple local services). Later, migrating to separate backend servers becomes much easier.<\/p>\n<h2><span id=\"Preparing_Your_Servers_OS_Security_and_DNS\">Preparing Your Servers: OS, Security and DNS<\/span><\/h2>\n<p>We will assume Ubuntu 22.04 or Debian 12 on all servers, but the Nginx configuration is almost identical on other modern Linux distributions.<\/p>\n<h3><span id=\"1_Provision_your_servers\">1. Provision your servers<\/span><\/h3>\n<p>You will need at least:<\/p>\n<ul>\n<li>1 VPS for the <strong>front Nginx reverse proxy<\/strong><\/li>\n<li>1 VPS for the <strong>backend application<\/strong>, ideally on the same data center or region for low latency<\/li>\n<\/ul>\n<p>For an illustrative small deployment, consider these initial allocations, then validate them against your workload:<\/p>\n<ul>\n<li><strong>Front Nginx VPS:<\/strong> 1\u20132 vCPU, 1\u20132 GB RAM<\/li>\n<li><strong>Backend VPS:<\/strong> 2\u20134 vCPU, 4\u20138 GB RAM (depending on language\/runtime and expected traffic)<\/li>\n<\/ul>\n<p>You can adjust these based on your actual usage; our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/how-much-cpu-ram-and-bandwidth-does-a-new-website-need\/\">how to estimate CPU, RAM and bandwidth for a new website<\/a> is a helpful reference when sizing.<\/p>\n<h3><span id=\"2_Secure_the_basics_on_each_VPS\">2. Secure the basics on each VPS<\/span><\/h3>\n<p>Before opening ports to the world, make sure you have the fundamentals in place:<\/p>\n<ul>\n<li>System fully updated (<code>apt update &amp;&amp; apt upgrade<\/code>, run with administrative privileges)<\/li>\n<li>Non-root user with sudo access<\/li>\n<li>SSH key authentication: verify a new key-authenticated administration session before disabling password login<\/li>\n<li>Firewall allowing only necessary ports (80\/443 on the front Nginx; app-specific ports only from the front proxy; SSH restricted to trusted administration sources). Preserve working administration access while applying the rules.<\/li>\n<\/ul>\n<p>If you want a concrete checklist, see our detailed post <a href=\"https:\/\/www.dchost.com\/blog\/en\/first-24-hours-on-a-new-vps-updates-firewall-and-users-step-by-step\/\">on what to do in the first 24 hours on a new VPS<\/a>. For a deeper dive into hardening, we also maintain a friendly guide on <a href=\"https:\/\/www.dchost.com\/blog\/en\/vps-security-checklist\/\">securing a VPS server without leaving doors open<\/a>.<\/p>\n<h3><span id=\"3_Configure_DNS\">3. Configure DNS<\/span><\/h3>\n<p>Point your domain (or subdomain) to the front Nginx VPS:<\/p>\n<ul>\n<li>Create an <strong>A<\/strong> record for each requested hostname, <code>example.com<\/code> and\/or <code>www.example.com<\/code>, pointing to the front VPS IPv4 address. The examples below show IPv4 listeners. Publish an <strong>AAAA<\/strong> record only after adding explicit IPv6 listeners and validating IPv6 routing, firewall access and HTTP\/HTTPS service for that hostname; DNS alone does not enable them.<\/li>\n<li>Backend servers do <strong>not<\/strong> need public DNS records; they can remain internal.<\/li>\n<\/ul>\n<p>After DNS points to the front server and Nginx is configured, HTTP\/HTTPS requests for those names can reach the proxy and be forwarded to your backends. DNS alone does not configure proxying or prevent direct access to a backend.<\/p>\n<h2><span id=\"StepbyStep_Nginx_as_a_Reverse_Proxy_to_a_Single_Backend\">Step\u2011by\u2011Step: Nginx as a Reverse Proxy to a Single Backend<\/span><\/h2>\n<p>First, we will configure Nginx to proxy traffic from the public internet to one backend application server. Later, we will turn this into a simple load balancer by adding more servers to the same upstream block.<\/p>\n<h3><span id=\"1_Install_Nginx_on_the_front_VPS\">1. Install Nginx on the front VPS<\/span><\/h3>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo apt update\nsudo apt install nginx -y\n<\/code><\/pre>\n<p>Enable and start Nginx if it\u2019s not already running:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo systemctl enable nginx\nsudo systemctl start nginx\n<\/code><\/pre>\n<p>You should now see the default Nginx welcome page when visiting your server IP in a browser.<\/p>\n<h3><span id=\"2_Define_your_backend_upstream\">2. Define your backend upstream<\/span><\/h3>\n<p>Assume your backend exposes HTTP on <code>10.0.0.10:8000<\/code> over a trusted private network. These addresses are illustrative; substitute your reachable backend address. A public backend address such as <code>192.0.2.11:8000<\/code> must be restricted to the front Nginx IP, but that firewall restriction does not encrypt traffic. The plain-HTTP upstream below is intended for a trusted private network or an encrypted tunnel, not an unencrypted public-internet hop.<\/p>\n<p>Create a new configuration file on the front server, for example:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo nano \/etc\/nginx\/conf.d\/app_upstream.conf\n<\/code><\/pre>\n<p>Add:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">upstream app_backend {\n    server 10.0.0.10:8000;\n}\n<\/code><\/pre>\n<p>This <code>upstream<\/code> block defines a logical name (<code>app_backend<\/code>) that points to your application server. Nginx will use it when proxying requests.<\/p>\n<h3><span id=\"3_Create_the_reverse_proxy_server_block\">3. Create the reverse proxy server block<\/span><\/h3>\n<p>Start with an HTTP-only <code>server<\/code> block that proxies to <code>app_backend<\/code>. Do not reference certificate files or enable HTTPS redirection before initial issuance succeeds. The next section uses the Certbot Nginx plugin to obtain and install TLS after this bootstrap passes validation. This is an initial setup on a fresh site; keep an existing live HTTPS configuration intact while preparing and testing changes.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo nano \/etc\/nginx\/sites-available\/example.com\n<\/code><\/pre>\n<p>For a new site, use this bootstrap in the site file created above. Confirm that the existing Nginx configuration includes the conf.d upstream file and sites-enabled site file in its HTTP context; enable this site through that existing include without duplicating a server block for the same names. Preserve a configuration backup, test with nginx -t and reload only after the test succeeds. Verify that each requested hostname reaches this HTTP site on port 80 before running Certbot. The HTTP bootstrap is for certificate setup, not login or payment traffic.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">server {\n    listen 80;\n    server_name example.com www.example.com;\n\n    add_header X-Frame-Options &quot;SAMEORIGIN&quot; always;\n    add_header X-Content-Type-Options &quot;nosniff&quot; always;\n\n    location \/ {\n        proxy_pass http:\/\/app_backend;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_set_header X-Forwarded-Host $host;\n\n        proxy_http_version 1.1;\n        proxy_set_header Connection &quot;&quot;;\n        proxy_read_timeout 60s;\n        proxy_send_timeout 60s;\n    }\n}\n<\/code><\/pre>\n<p>The preceding HTTP-only bootstrap must pass validation and serve both requested hostnames before certificate issuance. If validation fails, stop and correct the reported configuration error; do not continue with Certbot or load an invalid configuration.<\/p>\n<p>For related background on HTTP security headers such as <code>X-Frame-Options<\/code> and HSTS, browse the <a href=\"https:\/\/www.dchost.com\/blog\/\">DCHost blog<\/a>.<\/p>\n<h3><span id=\"4_Obtain_a_free_Lets_Encrypt_SSL_certificate\">4. Obtain a free Let\u2019s Encrypt SSL certificate<\/span><\/h3>\n<p>Install Certbot and the Nginx plugin:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo apt install certbot python3-certbot-nginx -y\n<\/code><\/pre>\n<p>Back up the Nginx configuration. With the validated HTTP site active, DNS pointing to this front VPS and inbound port 80 reachable for every requested name, run Certbot to obtain and install the certificate. Include only names you control and have configured:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo certbot --nginx -d example.com -d www.example.com\n<\/code><\/pre>\n<p>After successful issuance, inspect the Nginx changes made by the plugin, the certificate names and paths, and the HTTP-to-HTTPS behavior. Keep the existing application proxy settings. If managing certificate directives manually, use the actual full-chain and private-key files created for this certificate; do not guess a directory name or refer to files that do not exist.<\/p>\n<p>Test the configuration, then reload Nginx only if the test succeeds:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo nginx -t &amp;&amp; sudo systemctl reload nginx\n<\/code><\/pre>\n<p>Verify HTTPS externally for each configured hostname, inspect the served certificate and confirm that requests reach the intended HTTP backend. Check renewal scheduling and how renewed certificates are loaded for your Certbot installation; successful initial issuance alone does not verify future renewal. Retain the configuration backup for recovery.<\/p>\n<h3><span id=\"5_Configure_the_backend_application_to_trust_proxy_headers\">5. Configure the backend application to trust proxy headers<\/span><\/h3>\n<p>Most frameworks (Laravel, Symfony, Django, Express, Rails, etc.) need proxy trust configured to detect the client IP and HTTPS status correctly. Trust only the intended proxy sources and headers, rather than arbitrary headers supplied by clients.<\/p>\n<ul>\n<li>For PHP\/Laravel, use the intended HTTPS application URL and configure the exact proxy addresses and accepted forwarded headers using the trusted-proxy configuration for your installed Laravel version. The application URL alone does not establish proxy trust.<\/li>\n<li>For Express, trust only the front proxy&#8217;s source address as actually seen by the backend. For example, <code>app.set('trust proxy', ['10.0.0.5'])<\/code> assumes that 10.0.0.5 is that observed address; replace it with your deployment&#8217;s exact proxy address. Do not copy a broad private subnet or unrestricted true setting. If there is NAT or another proxy, verify the entire path before enabling trust.<\/li>\n<\/ul>\n<p>Before enabling application proxy trust, add <code>proxy_set_header X-Forwarded-Host $host;<\/code> alongside the existing Host, X-Real-IP, X-Forwarded-For and X-Forwarded-Proto lines in every relevant proxy location, including the earlier bootstrap and later routing examples. This replaces a client-supplied forwarded host; keep the existing X-Forwarded-Proto replacement. Validate and reload the completed Nginx configuration, restrict backend ingress to the intended proxy and configure the application&#8217;s allowed hostnames. With an exact proxy-address policy, Express examines X-Forwarded-For from right to left until the first untrusted address. Verify client IP, scheme and host with deliberately conflicting forwarded headers before relying on them.<\/p>\n<p>Correct proxy configuration avoids issues like infinite redirect loops or all visitors appearing to have the same IP address (the Nginx server\u2019s IP).<\/p>\n<h2><span id=\"Turning_the_Reverse_Proxy_into_a_Simple_Load_Balancer\">Turning the Reverse Proxy into a Simple Load Balancer<\/span><\/h2>\n<p>After the single-backend route works, you can add backend servers to the upstream group. First align their application versions and configuration, shared state and network access. Adding server lines alone does not make the application stateless or the front proxy redundant.<\/p>\n<h3><span id=\"1_Add_multiple_backend_servers_to_the_upstream\">1. Add multiple backend servers to the upstream<\/span><\/h3>\n<p>Edit the upstream definition:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo nano \/etc\/nginx\/conf.d\/app_upstream.conf\n<\/code><\/pre>\n<p>Change:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">upstream app_backend {\n    server 10.0.0.10:8000;\n}\n<\/code><\/pre>\n<p>To:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">upstream app_backend {\n    server 10.0.0.10:8000 max_fails=3 fail_timeout=30s;\n    server 10.0.0.11:8000 max_fails=3 fail_timeout=30s;\n}\n<\/code><\/pre>\n<p>By default, Nginx uses <strong>round-robin<\/strong> load balancing to distribute requests among available backends. With <code>max_fails=3<\/code> and <code>fail_timeout=30s<\/code>, three unsuccessful communication attempts within 30 seconds make a backend unavailable for 30 seconds; the failures need not be consecutive. This is passive failure handling, not a separate application-health probe. Failure accounting depends on <code>proxy_next_upstream<\/code>. Its default retry conditions are <code>error<\/code> and <code>timeout<\/code>, not all 5xx responses; counting 500\/502\/503\/504 responses requires explicitly selecting them, while 403\/404 never count as unsuccessful attempts. Switching backends cannot repair a response after data has reached the client. Non-idempotent requests such as POST are normally not retried once sent upstream; explicitly enabling such retries can duplicate side effects.<\/p>\n<h3><span id=\"2_Optional_Choose_a_different_load_balancing_method\">2. Optional: Choose a different load balancing method<\/span><\/h3>\n<p>Nginx supports several built-in algorithms for distributing requests:<\/p>\n<ul>\n<li><strong>Round-robin (default):<\/strong> Evenly rotates through servers. Good default choice.<\/li>\n<li><strong>least_conn:<\/strong> Sends new requests to the server with the fewest active connections. Useful for long-running requests (e.g. file uploads).<\/li>\n<li><strong>ip_hash:<\/strong> Provides basic affinity based on client IP, generally keeping requests from that IP on the same available backend. It is not durable session storage.<\/li>\n<\/ul>\n<p>To enable <code>least_conn<\/code>:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">upstream app_backend {\n    least_conn;\n    server 10.0.0.10:8000 max_fails=3 fail_timeout=30s;\n    server 10.0.0.11:8000 max_fails=3 fail_timeout=30s;\n}\n<\/code><\/pre>\n<p>To enable IP-based sticky sessions with <code>ip_hash<\/code>:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">upstream app_backend {\n    ip_hash;\n    server 10.0.0.10:8000 max_fails=3 fail_timeout=30s;\n    server 10.0.0.11:8000 max_fails=3 fail_timeout=30s;\n}\n<\/code><\/pre>\n<p>Treat <code>ip_hash<\/code> as basic affinity, not a guarantee of session continuity. Client IP changes, backend failures or changes to the backend set can disrupt affinity; shared session storage is the more robust approach when session continuity matters.<\/p>\n<h3><span id=\"3_Reload_Nginx_and_verify\">3. Reload Nginx and verify<\/span><\/h3>\n<p>Test the configuration and reload only if the test succeeds:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">sudo nginx -t &amp;&amp; sudo systemctl reload nginx\n<\/code><\/pre>\n<p>You can verify backend selection by checking application logs on each backend server, or by using a restricted diagnostic endpoint that identifies the instance handling the request. With <code>ip_hash<\/code>, repeated requests from one client IP are not expected to exercise both backends.<\/p>\n<h3><span id=\"4_Dealing_with_sticky_sessions_login_carts_etc\">4. Dealing with sticky sessions (login, carts, etc.)<\/span><\/h3>\n<p>If your application relies on backend-local sessions (for example, PHP sessions stored on local disk or Node.js sessions in memory), round-robin balancing can cause \u201crandom logouts\u201d or inconsistent cart behaviour. To avoid this:<\/p>\n<ul>\n<li>Use <strong>shared session storage<\/strong> (Redis, database) so any backend can handle any user.<\/li>\n<li>Or use <strong>sticky sessions<\/strong> with <code>ip_hash<\/code> in Nginx, understanding it\u2019s a basic solution tied to client IP.<\/li>\n<\/ul>\n<p>For production WooCommerce or complex carts, use shared session storage across backends. Treat response caching separately: personalised cart, checkout and account responses must not enter a shared public cache. Our post on <a href=\"https:\/\/www.dchost.com\/blog\/en\/containerizing-wordpress-on-one-vps-my-production-docker-playbook-with-traefik-or-nginx\/\">containerising WordPress with Nginx reverse proxy in front<\/a> and our various WooCommerce performance guides go deeper into how to design these layers cleanly.<\/p>\n<h2><span id=\"Routing_Multiple_Apps_Behind_One_Nginx_Reverse_Proxy\">Routing Multiple Apps Behind One Nginx Reverse Proxy<\/span><\/h2>\n<p>A big advantage of this pattern is that you can host multiple services behind the same front Nginx, each on its own backend or port. Common scenarios:<\/p>\n<ul>\n<li><strong>SPA + API:<\/strong> A Vue\/React frontend on one backend and an API (Laravel, Node.js) on another.<\/li>\n<li><strong>Admin vs public site:<\/strong> Admin panel and public site on separate servers for security or performance reasons.<\/li>\n<li><strong>Legacy + new app:<\/strong> Old application and new microservice running side by side.<\/li>\n<\/ul>\n<h3><span id=\"1_Path-based_routing\">1. Path-based routing<\/span><\/h3>\n<p>Example: <code>\/<\/code> goes to the main PHP app and <code>\/api\/<\/code> goes to a Node.js API. Both upstreams must expose HTTP services: the PHP upstream on port 9000 represents an HTTP server serving the app, not a PHP-FPM listener. This is a routing fragment; supply the omitted SSL configuration before using the HTTPS server block.<\/p>\n<p>The trailing slash in <code>proxy_pass http:\/\/node_api\/;<\/code> replaces the matching <code>\/api\/<\/code> prefix with <code>\/<\/code>: an ordinary request for \/api\/users reaches the backend as \/users. The Node.js application must expect root-relative routes. If it expects \/api\/users, use <code>proxy_pass http:\/\/node_api;<\/code> without a URI instead. Choose one behavior to match the application and test real routes, redirects and generated asset URLs; a reachable backend does not establish a correct path mapping.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">upstream php_app {\n    server 10.0.0.10:9000;\n}\n\nupstream node_api {\n    server 10.0.0.20:3000;\n}\n\nserver {\n    listen 443 ssl http2;\n    server_name example.com;\n\n    # SSL config omitted for brevity\n\n    location \/api\/ {\n        proxy_pass http:\/\/node_api\/;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_set_header X-Forwarded-Host $host;\n    }\n\n    location \/ {\n        proxy_pass http:\/\/php_app\/;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_set_header X-Forwarded-Host $host;\n    }\n}\n<\/code><\/pre>\n<p>After integrating the routing fragment with the complete existing HTTPS configuration, run <code>sudo nginx -t &amp;&amp; sudo systemctl reload nginx<\/code> and proceed only if validation succeeds. Verify both application roots and nested API routes. The guide to <a href=\"https:\/\/www.dchost.com\/blog\/en\/why-put-the-spa-and-api-on-one-domain\/\">hosting single-page applications and APIs under one domain with Nginx routing<\/a> discusses this shared-origin pattern.<\/p>\n<h3><span id=\"2_Hostname-based_routing\">2. Hostname-based routing<\/span><\/h3>\n<p>You can also route based on <strong>hostnames<\/strong> instead of paths. For example, <code>app.example.com<\/code> and <code>api.example.com<\/code> can each have their own <code>server<\/code> block with different <code>proxy_pass<\/code> targets, while still using the same front Nginx instance and IP address.<\/p>\n<p>For each hostname, prepare its DNS, matching certificate and complete server block, and apply the same proxy-header and backend-access restrictions. Separate hostnames or paths alone do not authorize access to an admin application; retain application authentication and authorization.<\/p>\n<h2><span id=\"Performance_Tuning_Timeouts_Caching_and_Logs\">Performance Tuning: Timeouts, Caching and Logs<\/span><\/h2>\n<p>The following timeout and caching settings are starting points to evaluate against your application&#8217;s workload.<\/p>\n<h3><span id=\"1_Reasonable_timeouts\">1. Reasonable timeouts<\/span><\/h3>\n<p>Choose timeouts to suit your workload rather than assuming the defaults fit. These example values belong in your <code>location<\/code> block:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">proxy_connect_timeout   5s;\nproxy_send_timeout      60s;\nproxy_read_timeout      60s;\nsend_timeout            60s;\n<\/code><\/pre>\n<p>If your app regularly needs longer than 60 seconds to respond, it\u2019s usually better to move heavy work to background jobs rather than just increasing timeouts. Our write-up on <a href=\"https:\/\/www.dchost.com\/blog\/en\/laravel-queues-supervisor-systemd-pm2\/\">why background jobs matter so much on a VPS<\/a> gives practical patterns for moving slow tasks out of the request\/response path.<\/p>\n<h3><span id=\"2_Microcaching_for_dynamic_sites\">2. Microcaching for dynamic sites<\/span><\/h3>\n<p><strong>Microcaching<\/strong> caches dynamic responses for a short period, such as 1\u20135 seconds. For cacheable public news pages, product listings or homepages, it can reduce backend load when requests reuse cached responses. Measure the benefit for your workload and choose an acceptable freshness window. A short lifetime does not make personalised or authenticated responses safe for a shared public cache.<\/p>\n<p>The following schematic defines a cache zone and enables it for a location serving only public responses that are identical for all users. Integrate the cache-path directive in the HTTP context and the location in the existing complete HTTPS site; retain actual certificates, timeouts and other required settings. Confirm the cache directory can be used by the Nginx worker under your package\u2019s permission model. The explicit cache key includes scheme, method, host and request URI so different site names do not share a key merely because they use the same backend.<\/p>\n<p>Do not apply this unchanged to a mixed public\/private site: it contains no application-specific rules to bypass cache reads and writes for logged-in users, carts or personalized responses. A location-level add_header also prevents the earlier server-level add_header values from being inherited under the default rules used here. The two earlier security headers are therefore repeated beside X-Cache-Status; retain any additional required header policy at this level as well.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">proxy_cache_path \/var\/cache\/nginx levels=1:2 keys_zone=microcache:10m max_size=1g inactive=60s use_temp_path=off;\n\nserver {\n    # ...\n    location \/ {\n        proxy_cache microcache;\n        proxy_cache_key &quot;$scheme$request_method$host$request_uri&quot;;\n        proxy_cache_valid 200 1s;\n        proxy_cache_valid 301 302 10s;\n        proxy_cache_valid any 0s;\n        add_header X-Cache-Status $upstream_cache_status;\n        add_header X-Frame-Options &quot;SAMEORIGIN&quot; always;\n        add_header X-Content-Type-Options &quot;nosniff&quot; always;\n\n        proxy_pass http:\/\/app_backend;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_set_header X-Forwarded-Host $host;\n    }\n}\n<\/code><\/pre>\n<p>After editing, run <code>sudo nginx -t &amp;&amp; sudo systemctl reload nginx<\/code> only with successful validation. Check the expected cache status and security headers on public responses and error paths. Test authenticated and personalized flows separately before extending caching to an application that has them. The <a href=\"https:\/\/www.dchost.com\/blog\/en\/the-1-5-second-miracle-how-nginx-microcaching-makes-php-feel-instantly-faster\/\">Nginx microcaching guide<\/a> covers bypassing, purging and logged-in user handling; measure performance with your own workload.<\/p>\n<h3><span id=\"3_Logging_and_observability\">3. Logging and observability<\/span><\/h3>\n<p>Nginx access and error logs are your first line of insight into what\u2019s happening:<\/p>\n<ul>\n<li>Monitor <code>\/var\/log\/nginx\/access.log<\/code> for status codes and traffic peaks; response times require timing fields in the configured log format.<\/li>\n<li>Monitor <code>\/var\/log\/nginx\/error.log<\/code> for upstream timeouts, connection errors, and misconfigurations.<\/li>\n<\/ul>\n<p>Add <code>$upstream_response_time<\/code> and <code>$request_time<\/code> to your log format to compare upstream response duration with total request duration; their difference is not a direct measure of Nginx processing time. For larger setups, logs can be shipped into a central system (Loki, ELK, etc.), but for small projects, even basic log review plus tools like <code>goaccess<\/code> or simple shell filters can reveal a lot.<\/p>\n<p>If you want to understand web server logs more deeply, we covered this step-by-step in <a href=\"https:\/\/www.dchost.com\/blog\/en\/apache-nginx-logs-4xx-5xx-errors\/\">our guide to reading web server logs and diagnosing 4xx\u20135xx errors on Apache and Nginx<\/a>.<\/p>\n<h2><span id=\"Hosting_Different_Stacks_Behind_Nginx\">Hosting Different Stacks Behind Nginx<\/span><\/h2>\n<p>One strength of this architecture is that Nginx doesn\u2019t care what technology your backend uses\u2014as long as it speaks HTTP. A few example backend arrangements:<\/p>\n<ul>\n<li><strong>PHP (Laravel, Symfony, WordPress):<\/strong> The front Nginx proxies HTTP requests to a web server on the backend VPS, which passes PHP requests to PHP-FPM via FastCGI.<\/li>\n<li><strong>Node.js (Express, NestJS, Next.js):<\/strong> Nginx proxies to one or more Node.js processes managed with PM2 or systemd.<\/li>\n<li><strong>Python (Django, Flask, FastAPI):<\/strong> Nginx proxies to Gunicorn\/Uvicorn workers. A localhost listener works only when the proxy connecting to it is on the same host; a separate front VPS needs a reachable backend HTTP listener with access restricted to the proxy.<\/li>\n<\/ul>\n<p>For a detailed Node.js example behind Nginx, you can check our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/how-i-host-node-js-in-production-without-drama-pm2-systemd-nginx-ssl-and-zero-downtime-deploys\/\">hosting Node.js in production with PM2, Nginx, SSL, and zero\u2011downtime deploys<\/a>. The reverse proxy layer is the same pattern we\u2019ve been describing here.<\/p>\n<h2><span id=\"When_to_Evolve_Beyond_This_Simple_Architecture\">When to Evolve Beyond This Simple Architecture<\/span><\/h2>\n<p>The Nginx reverse proxy + simple load balancer pattern scales surprisingly far for small and medium projects, but there are clear signs when you should consider the next step:<\/p>\n<ul>\n<li><strong>Single front VPS becomes a bottleneck:<\/strong> CPU, RAM, or network usage on the Nginx front server stays high, even after tuning and microcaching.<\/li>\n<li><strong>Need for high availability:<\/strong> You cannot accept a single point of failure on the front proxy, and you want automatic failover between multiple front nodes.<\/li>\n<li><strong>Complex routing and security rules:<\/strong> Many apps, custom WAF rules, geo\u2011routing, or advanced rate limiting might require a more specialised setup.<\/li>\n<li><strong>Multi\u2011region or multi\u2011data center deployments:<\/strong> You need geographic or latency-aware routing policies; DNS\u2011level balancing alone does not guarantee that each user reaches the closest region.<\/li>\n<\/ul>\n<p>At that stage, you might introduce a second Nginx front with anycast or DNS failover, or look at dedicated load balancers or Kubernetes-based approaches.<\/p>\n<h2><span id=\"Summary_and_How_dchostcom_Fits_In\">Summary and How dchost.com Fits In<\/span><\/h2>\n<p>A dedicated Nginx reverse proxy and simple load balancer in front of your application servers can provide a manageable foundation for small projects. You centralise SSL, control routing in one place, gain the ability to add or remove backend servers, and open the door to microcaching and fine-grained security headers\u2014all while keeping the design understandable for a small team.<\/p>\n<p>The steps we covered\u2014preparing secure VPS servers, defining upstream blocks, configuring reverse proxy server blocks, adding basic load balancing, and adding small performance optimisations\u2014form an incremental deployment path. You can start with a single VPS, split out Nginx to a front server when traffic warrants it, and then incrementally add more backends or caching as your needs grow.<\/p>\n<p>If you are planning a new project or splitting an existing \u201call-in-one\u201d server, DCHost offers self-managed VPS plans that you can evaluate for this architecture. Size the front and backend servers for your workload and confirm networking requirements before choosing a plan. Operating-system, application, security, and data-protection administration remain your responsibility unless a separate service is agreed.<\/p>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Build a small-project Nginx front proxy, then add backend load balancing. The guide covers HTTPS setup, proxy trust, routing, shared sessions and caching boundaries while explaining the single-front-server limitation.<\/p>\n","protected":false},"author":1,"featured_media":12490,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[184],"tags":[],"class_list":["post-3523","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3523","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/comments?post=3523"}],"version-history":[{"count":4,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3523\/revisions"}],"predecessor-version":[{"id":12693,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3523\/revisions\/12693"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media\/12490"}],"wp:attachment":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media?parent=3523"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/categories?post=3523"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/tags?post=3523"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}