AI Prompt Engineering

Getting ChatGPT to Write Accurate Nginx Configs Without Broken Routing

June 27, 2026 10 min read 11 views

You ask ChatGPT for an Nginx reverse proxy config, paste it into your server, and suddenly half your routes return 404s or your upstream gets a garbled request path. The config looks right, but something is off. That's the Nginx trap: small mistakes in directive order or a trailing slash in the wrong place produce silent routing failures that are painful to trace.

This guide shows you how to write prompts that give ChatGPT enough context to generate correct Nginx configs, and how to verify what it produces before it ever touches a live server.

What You'll Learn

  • Why ChatGPT's default Nginx output tends to have subtle routing bugs
  • How to structure prompts with the architecture detail ChatGPT needs
  • The most dangerous Nginx directives to double-check in AI output
  • How to validate a generated config before deploying it
  • Prompt templates for reverse proxy, SSL termination, and upstream load balancing

Prerequisites

You should be comfortable with basic Nginx concepts: server blocks, location blocks, and the idea of a reverse proxy. You don't need to be an Nginx expert — that's the point of using ChatGPT — but you do need to know what your intended routing should look like so you can verify the output.

How ChatGPT Thinks About Nginx (And Where It Goes Wrong)

ChatGPT has seen a large volume of Nginx configuration examples in its training data. Most of that data is tutorial-grade material — clean, simple, single-server setups that work for a basic demo. Your production setup is almost certainly more complex: multiple upstreams, path-based routing, custom headers, WebSocket upgrades, and SSL termination all in the same file.

When you give ChatGPT a vague prompt like "write me an Nginx reverse proxy config", it defaults to the most common pattern it knows. That pattern is often technically valid but wrong for your specific case. The two failure modes you'll hit most often:

  • Wrong location block specificity: ChatGPT may order blocks in a way that causes a more-general pattern to match before a more-specific one.
  • Trailing slash inconsistency in proxy_pass: Whether you include a trailing slash after the upstream address completely changes how Nginx rewrites the URI. ChatGPT frequently gets this wrong or inconsistently explains it.

The fix is not to give up on ChatGPT for Nginx configs. It's to give it the context it needs to pick the right pattern. This is the same principle that applies when you ask it to generate other infrastructure configs — as covered in the guide on getting ChatGPT to write accurate Terraform configs without stale provider syntax.

Building a Prompt That Gets Accurate Configs

A good Nginx prompt is specific about three things: the topology (what talks to what), the routing rules (which paths go where), and any constraints (Nginx version, modules available, headers to preserve). Without all three, ChatGPT will make assumptions that may not match your environment.

Give ChatGPT Your Exact Architecture

Start by describing your infrastructure in concrete terms before asking for any config. Include the number of upstream services, which ports they listen on, the domain names involved, and whether you're doing path-based or subdomain-based routing.

Context:
- Nginx 1.24 running on Ubuntu 22.04
- Domain: api.example.com
- Two backend services:
    /api/v1/ → Node.js app on 127.0.0.1:3000
    /api/v2/ → Python FastAPI app on 127.0.0.1:8000
- All traffic arrives on HTTPS (SSL terminated at Nginx)
- HTTP should redirect to HTTPS
- Do NOT strip the path prefix before forwarding to upstreams

Generate a complete Nginx server block for this setup.
Include upstream blocks, proxy headers, and the SSL redirect.
Use only directives available in the standard nginx package (no extra modules).

The last line matters. If you don't specify standard modules only, ChatGPT may include directives like ngx_http_auth_request_module or Lua-based logic that your binary doesn't have compiled in.

Specify Directive Constraints Explicitly

Tell ChatGPT what you need preserved. If your upstream depends on the original Host header, say so. If you're running a WebSocket service behind Nginx, say so — otherwise it won't add the Upgrade and Connection headers. If you need X-Forwarded-For passed through, say so.

Additional constraints:
- Preserve the original Host header: proxy_set_header Host $host;
- Pass real client IP: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- /api/v1/ws/ must support WebSocket upgrades
- Set proxy_read_timeout to 60s
- Do not add any access_log or error_log directives (managed separately)

By listing what you don't want (like log directives), you prevent ChatGPT from filling in defaults that conflict with your existing global nginx.conf.

Anatomy of a Reliable Reverse Proxy Config

Once you have a prompt that gives ChatGPT enough to work with, it will usually produce something close to correct. Here's what the output should look like for the architecture described above, and what to check in each section.

The proxy_pass Trailing-Slash Trap

This is the most common source of silent routing bugs in ChatGPT-generated Nginx configs. The difference between these two directives is significant:

# Without trailing slash — Nginx forwards the full URI as-is
location /api/v1/ {
    proxy_pass http://127.0.0.1:3000;
}

# With trailing slash — Nginx strips the location prefix before forwarding
location /api/v1/ {
    proxy_pass http://127.0.0.1:3000/;
}

In the first form, a request for /api/v1/users arrives at your Node app as /api/v1/users. In the second form, it arrives as /users. If your app expects /users but gets /api/v1/users, every route returns 404. ChatGPT will sometimes mix these within the same config, or use the wrong one for your setup without explanation.

Always check: does your upstream app expect the prefix stripped or preserved? Then verify the trailing slash matches that expectation.

Location Block Order and Specificity

Nginx evaluates location blocks in a specific order: exact matches (=) first, then prefix matches ordered by length (longest wins), then regex matches in the order they appear. ChatGPT sometimes generates a config where a short prefix match appears before a longer, more-specific one using regex notation, which causes the wrong block to win.

# Correct: more-specific prefix wins because Nginx picks longest match
location /api/v2/ {
    proxy_pass http://127.0.0.1:8000;
}

location /api/v1/ {
    proxy_pass http://127.0.0.1:3000;
}

# Dangerous: a regex match will shadow prefix matches that appear later
location ~ ^/api/ {
    proxy_pass http://127.0.0.1:3000;  # This catches /api/v2/ too
}

location /api/v2/ {
    proxy_pass http://127.0.0.1:8000;  # Never reached
}

If your generated config mixes prefix and regex location blocks, trace through each one mentally with a sample request path and confirm the right block wins.

Handling SSL Termination and HTTPS Redirects

ChatGPT can produce a functional SSL config, but it sometimes outputs patterns that are subtly outdated — like including ssl on; (deprecated since Nginx 1.15.0) or using a cipher list that hasn't been reviewed in years. Ask explicitly for a modern TLS setup.

server {
    listen 80;
    server_name api.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name api.example.com;

    ssl_certificate     /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    location /api/v1/ {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /api/v2/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Notice X-Forwarded-Proto $scheme — your backend needs this to know the original request was HTTPS, especially if it generates redirect URLs. ChatGPT omits it surprisingly often.

Upstreams, Load Balancing, and Health Checks

If you have multiple instances of an upstream service, describe the load balancing strategy explicitly in your prompt. ChatGPT defaults to round-robin if you don't specify, which may not be what you want. Specify whether you need least_conn, ip_hash for sticky sessions, or a weighted distribution.

upstream node_backend {
    least_conn;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002;
    server 127.0.0.1:3003;
    keepalive 32;
}

server {
    listen 443 ssl;
    # ... ssl config ...

    location /api/v1/ {
        proxy_pass http://node_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

The proxy_http_version 1.1 and proxy_set_header Connection "" pair is required for upstream keepalive connections to work. ChatGPT will sometimes generate the keepalive directive in the upstream block but forget to add the corresponding proxy directives that activate it. Always check that these travel together.

Note that Nginx's built-in health_check directive requires the commercial Nginx Plus subscription. The open-source version does passive health checks only (failed connections mark a server as down temporarily). If ChatGPT generates an active health_check block, that's a sign it's mixing up open-source and Plus features.

Common Pitfalls ChatGPT Introduces

Beyond the routing issues covered above, watch for these patterns in generated configs:

  • Missing proxy_http_version 1.1 for WebSocket: WebSocket upgrades require HTTP/1.1. Without it, the upgrade handshake fails silently. This issue is similar to what happens with dropped messages in WebSocket handlers — the handshake looks fine at first glance but breaks under the hood.
  • try_files used with proxy_pass: These two directives do not compose cleanly. ChatGPT sometimes puts both in the same location block, which causes Nginx to try the filesystem first and only proxy on failure. This is rarely what you want for an API endpoint.
  • Hardcoded IP addresses without upstream blocks: Direct proxy_pass http://10.0.0.5:3000 in a location block makes it impossible to add failover later. Always use an upstream block, even for a single server.
  • Missing include mime.types: When ChatGPT generates a minimal http block, it sometimes omits the mime types include. Static files will be served as application/octet-stream.
  • Default server_name _: Using underscore as a catch-all server name is fine for a default block, but ChatGPT sometimes applies it to your primary server block, which silently accepts requests for any hostname.

Validating the Output Before You Deploy

Never paste a ChatGPT-generated Nginx config directly into a production server. Run it through a validation sequence first.

Step 1: Syntax check. Copy the config to a test file and run nginx -t -c /path/to/test.conf. This catches directive typos and structural errors immediately.

sudo nginx -t -c /etc/nginx/sites-available/api.example.com
# Expected: nginx: configuration file ... test is successful

Step 2: Trace each routing rule manually. For every location block, write down a sample request path and follow the Nginx matching rules to confirm the right block wins. A tool like step-by-step config validation thinking applies here too — don't skip this because the syntax check passed.

Step 3: Ask ChatGPT to explain its own config. This is genuinely useful. After generating the config, ask: "For a request to GET /api/v2/products, walk through exactly which location block matches and what URL the upstream receives." If the explanation doesn't match what you expect, the config needs revision. This follow-up prompt catches subtle proxy_pass URI rewriting issues faster than manual inspection.

Step 4: Test with curl against a staging server. Use -v to see request and response headers, and verify that X-Forwarded-For, X-Forwarded-Proto, and Host headers arrive at your upstream with the correct values.

curl -v https://api.example.com/api/v1/health
# Check: upstream receives correct path, headers are present

This validation loop also applies when you're generating other types of infrastructure configs. The guide on getting ChatGPT to write accurate Docker configs covers a similar review process for container configuration.

Wrapping Up: Next Steps

ChatGPT is a capable starting point for Nginx configuration, but it needs precise input to avoid the common failure modes. Here's what to do from here:

  1. Build a prompt template specific to your infrastructure topology. Include your Nginx version, upstream services with ports, routing rules, and header requirements. Save it and reuse it whenever you need a new config.
  2. Always check proxy_pass trailing slashes against what your upstream expects. This single directive accounts for a large proportion of 404s in AI-generated reverse proxy configs.
  3. Run nginx -t before every apply, and add a manual routing trace for any location block you didn't write yourself.
  4. Use the explanation follow-up prompt: ask ChatGPT to walk through a sample request path after generating the config. This is the fastest way to catch URI rewriting bugs.
  5. Keep a validated config snippet library — once a config works for a specific pattern (SSL termination, WebSocket upstream, load-balanced backend), save it. Use ChatGPT to adapt a known-good template rather than generating from scratch each time.

Frequently Asked Questions

Why does ChatGPT keep generating Nginx configs with the wrong proxy_pass URI rewriting?

ChatGPT often defaults to a common tutorial pattern without knowing whether your upstream expects the path prefix preserved or stripped. Explicitly tell it in your prompt whether to include a trailing slash after the upstream address, and ask it to explain the URI rewriting behavior for a sample request so you can verify it matches your expectation.

How do I get ChatGPT to generate Nginx location blocks in the correct matching order?

Describe your routing rules in priority order in the prompt and specify whether you need prefix or regex matching. Then ask ChatGPT to list, for each block, what type of match it uses and which sample paths it would catch — this surfaces ordering conflicts before you deploy.

Can ChatGPT generate Nginx configs with WebSocket support that actually work?

Yes, but you must explicitly request WebSocket support in your prompt and mention the specific path that needs the upgrade. ChatGPT will otherwise omit the Upgrade and Connection headers required for the WebSocket handshake, and it must also include proxy_http_version 1.1 for the upgrade to succeed.

What Nginx directives should I always double-check in AI-generated configs?

Always verify proxy_pass (trailing slash and URI rewriting), location block order (prefix vs regex conflicts), ssl_protocols (ensure TLSv1.2 and TLSv1.3 only), and any upstream keepalive settings paired with proxy_http_version 1.1. These are the most common sources of silent routing bugs in generated configs.

How can I validate a ChatGPT-generated Nginx config without deploying it to production?

Run nginx -t against the config file on a non-production server to catch syntax errors, then manually trace each location block with a sample request path to confirm the correct block matches. Using curl -v against a staging server lets you verify that proxy headers and URI paths arrive at the upstream as expected.

📤 Share this article

Sign in to save

Comments (0)

No comments yet. Be the first!

Leave a Comment

Sign in to comment with your profile.

📬 Weekly Newsletter

Stay ahead of the curve

Get the best programming tutorials, data analytics tips, and tool reviews delivered to your inbox every week.

No spam. Unsubscribe anytime.