Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Redirect an IP and Port URL to a Flask API With Nginx

A practical Nginx and Gunicorn configuration for exposing a Flask API through an IP address or hostname, with HTTPS redirects, forwarded headers, firewall rules, validation, and failure fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Nginx as the public entry point and Gunicorn as the private WSGI server. Nginx listens on port 80 (and, for HTTPS, 443), while Gunicorn serves Flask on 127.0.0.1:8000 or a Unix socket. Nginx then proxies each request to that private listener, so clients keep using your IP address or domain name.

HTTP-to-HTTPS redirection and reverse proxying are separate jobs: a 301 response sends the browser to another URL, whereas proxy_pass fetches the Flask response while keeping the public URL unchanged. The configurations below show both patterns, secure forwarded-header handling, validation, and fixes for common deployment failures.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the public URL reaches Flask

A production request normally follows this path:

  1. The client requests http://SERVER_IP, http://SERVER_IP:80, or a hostname such as api.example.com.
  2. Nginx accepts the public connection on port 80 or 443.
  3. For an HTTPS request, Nginx terminates TLS and decrypts the HTTP request.
  4. Nginx forwards the request over the loopback interface to Gunicorn at 127.0.0.1:8000, or through a Unix socket.
  5. Gunicorn runs the Flask application and returns the response to Nginx, which sends it to the client.

Gunicorn should not run as root. It is a WSGI server rather than a public edge server, so placing Nginx in front provides the public listeners, TLS handling, and request-processing controls. A non-root Gunicorn process cannot normally bind directly to privileged ports 80 or 443.

Redirect and reverse proxy are different operations

Operation What the client sees Typical Nginx directive Use it when
HTTP redirect The client receives a 301 or 302 response and makes a new request to the URL in the Location header. return 301 https://$host$request_uri; You want port 80 traffic to move to HTTPS.
Reverse proxy The public URL stays in the browser; Nginx retrieves the response from the private Flask service. proxy_pass http://127.0.0.1:8000/; You want the public IP or hostname to expose the API without exposing Gunicorn.

Redirecting port 80 to HTTPS does not, by itself, connect Flask to Nginx. The HTTPS server block still needs a proxy_pass directive. Conversely, a plain HTTP proxy can serve the API without redirecting anywhere, although production APIs should use TLS.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

What you need before editing Nginx

  • A Flask application that Gunicorn can import, such as an application object exposed by your chosen module.
  • Gunicorn running under a dedicated, non-root account.
  • A private Gunicorn listener at 127.0.0.1:8000 or a Unix socket owned by the Nginx worker account.
  • Nginx installed and able to bind to ports 80 and, if used, 443.
  • DNS pointing the API hostname at the server when you use a domain instead of an IP address.
  • A certificate and private key whose names match the HTTPS hostname or address clients request.
  • A firewall policy that exposes Nginx ports 80 and 443 but does not expose the Gunicorn port.

The examples use api.example.com for a hostname and SERVER_IP for an address. Replace those values with your actual endpoint. If you use an IP-only URL, make the certificate and client URL match that IP; a hostname is usually simpler for certificate management.

Step 1: keep Gunicorn private

Start Gunicorn through your service manager or deployment process with a bind address such as 127.0.0.1:8000. The loopback address means only processes on the same server can connect. Do not bind the application to 0.0.0.0:8000 unless you deliberately need remote access and have separately protected that port.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Unix socket is another private option. It removes a TCP port from the application side, but the socket file must be readable and writable by the Nginx worker account. Incorrect ownership or mode settings commonly produce a 502 error even when Gunicorn is running.

Confirm that the service is actually listening on the address configured in Nginx before troubleshooting Nginx itself. A mismatch such as Gunicorn on port 8001 while Nginx proxies to 8000 produces the same gateway symptom as a stopped service.

Step 2: proxy an IP or hostname over HTTP

For a simple HTTP deployment, create a server block that listens on port 80 and proxies the root path to Gunicorn:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
server {
    listen 80;
    server_name _;

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

server_name _; acts as a catch-all for an IP-based request or an otherwise unmatched host. For a named API, replace it with server_name api.example.com;. The proxy_pass value accepts an IP address or hostname and may include a port. The trailing slash in this example works with location / and forwards the request into the upstream root.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After saving the server block, enable it using your operating system’s normal Nginx layout, then validate the complete configuration before reloading. Do not skip validation: a syntax error can prevent the reload and leave the previous configuration active.

Step 3: redirect port 80 to HTTPS and proxy on 443

For a production hostname, use one server block only to redirect clear-text requests and another to terminate TLS and proxy to Gunicorn:

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/ssl/certs/api.example.com.pem;
    ssl_certificate_key /etc/ssl/private/api.example.com.key;

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

The first block returns the original path and query string through $request_uri, so a request such as http://api.example.com/v1/items?page=2 is redirected to the corresponding HTTPS URL. The second block terminates TLS and performs the actual proxying. Use certificate paths that exist on your server and are readable by Nginx.

If you intentionally serve an IP address rather than a hostname, use that address in the relevant server_name and obtain a certificate that covers the address. Otherwise clients may receive a certificate-name warning even though the proxy is functioning.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Forward the original request context

The upstream connection originates at Nginx, so Flask would otherwise see the proxy’s address, scheme, and host. Forward these values explicitly:

Header Purpose Value in the example
X-Forwarded-For Preserves the client address while appending each proxy in the chain. $proxy_add_x_forwarded_for
X-Forwarded-Proto Tells Flask whether the external request used HTTP or HTTPS. $scheme
X-Forwarded-Host Preserves the host requested by the client. $host
X-Forwarded-Prefix Describes a path prefix added by the proxy. / for the root-mounted example.

Forwarding Host explicitly can also be useful when the application relies on the standard host header:

proxy_set_header Host $host;

Keep the header policy consistent across every Nginx server block that fronts the application. Missing or contradictory values are a common reason for generated links using the wrong scheme or hostname.

Make Flask trust only the proxies you operate

Flask’s ProxyFix middleware can replace the WSGI request values with forwarded values, but it must be configured for the real proxy chain. A single Nginx instance directly in front of Gunicorn is commonly one trusted proxy; a load balancer plus Nginx is a different chain and requires different counts.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(
    app.wsgi_app,
    x_for=1,
    x_proto=1,
    x_host=1,
    x_prefix=1,
)

Set only the fields you actually forward and set each count to the number of trusted proxies that add that field. Never enable a high count merely to make a header appear correct. If an untrusted client can inject a value that ProxyFix accepts, it may influence URL generation, scheme checks, host validation, logging, or access-control decisions. Nginx and Gunicorn guidance both warn that forged forwarded headers are dangerous.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Rewrite upstream redirects when necessary

Some Flask responses or extensions emit a Location header containing an internal address such as http://localhost:8000/. A browser cannot use that private address as the public API endpoint. Nginx’s proxy_redirect directive can replace an upstream URL with the public one:

location / {
    proxy_pass http://127.0.0.1:8000/;
    proxy_redirect http://localhost:8000/ https://api.example.com/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Prefix /;
}

Use a replacement that matches the internal URL your application actually emits and the external scheme and host clients should receive. Do not add a broad rewrite rule when the application already generates correct public URLs; diagnose the specific Location value first.

Firewall and exposure rules

Expose only the Nginx edge ports to the public network:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Allow inbound TCP 80 when you serve HTTP or need the HTTP-to-HTTPS redirect.
  • Allow inbound TCP 443 when you serve HTTPS.
  • Block inbound TCP 8000 and any other Gunicorn port from public networks.
  • Keep Gunicorn bound to loopback or a protected private interface.
  • If you use a Unix socket, restrict its directory and file permissions to the Gunicorn and Nginx accounts.

These controls ensure requests cannot bypass Nginx, TLS termination, header normalization, or access logging by connecting directly to Gunicorn.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate, reload, and observe the deployment

  1. Run nginx -t and correct every reported syntax, include, certificate-path, or permission error.
  2. Reload Nginx through your service manager only after the test succeeds. A reload applies the new configuration without requiring a full stop.
  3. Request the public HTTP URL and verify that the response is a redirect when you configured the port-80 redirect block.
  4. Request the HTTPS URL and verify that the response is produced by Flask rather than an Nginx default page.
  5. Check Nginx access and error logs together with the Gunicorn service log. The matching timestamps show whether a request reached the proxy and whether the upstream returned a response.
  6. Test a route that generates an absolute URL or redirect, and confirm it uses the public HTTPS host rather than 127.0.0.1:8000.

Do not treat a successful nginx -t as proof that the application is reachable. The test checks configuration syntax; only an end-to-end request confirms listener availability, socket permissions, headers, TLS, and application behavior.

Diagnose common failures

Symptom Likely cause What to check
502 Bad Gateway Gunicorn is stopped, listening on another address or port, or Nginx cannot access the Unix socket. Confirm the Gunicorn bind value, service status, socket existence, and socket ownership or mode. Compare it with proxy_pass.
Redirect loop The application believes an HTTPS request is HTTP and redirects again. Forward X-Forwarded-Proto $scheme and configure ProxyFix with the correct trusted-proxy count. Ensure the TLS server proxies directly instead of redirecting itself.
HTTPS page contains HTTP links Flask is not receiving or trusting the original scheme. Check the forwarded-proto header, ProxyFix settings, and any application URL-generation configuration.
Location exposes an internal host or port The upstream generated a private URL. Inspect the response header and add a narrowly scoped proxy_redirect replacement, or correct application URL generation.
Application always logs 127.0.0.1 The client address was not forwarded or Flask is not trusting the forwarded chain. Verify X-Forwarded-For $proxy_add_x_forwarded_for and the ProxyFix x_for count.
Requests reach Gunicorn without Nginx The Gunicorn port is publicly bound or the firewall permits it. Bind to loopback or private networking and block the application port at the firewall.
Nginx reload fails Syntax errors, duplicate listeners, missing include files, or unreadable certificate files. Run nginx -t, read the exact error, and fix the referenced file or permission before retrying.

Use a Unix socket instead of port 8000

A Unix socket is useful when Nginx and Gunicorn share a host and you want the application endpoint to be a filesystem object rather than a TCP listener. The Nginx location then points to a socket URL, for example:

location / {
    proxy_pass http://unix:/run/my-flask-api/gunicorn.sock:;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Prefix /;
}

The exact socket path must match the Gunicorn service. Ensure the parent directory permits Nginx traversal and the socket permits Nginx access. If those permissions are wrong, Nginx reports a gateway failure even though the Gunicorn process is healthy. A loopback TCP listener is usually easier to inspect and is perfectly suitable when both services run on one machine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Self-managed Nginx/Gunicorn or managed Flask hosting?

A self-managed reverse proxy gives you direct control over listeners, headers, firewall rules, certificates, process boundaries, and network layout. It also makes you responsible for operating-system updates, Nginx and Gunicorn updates, certificate renewal, log retention, incident response, and recovery when a service stops.

Managed Python hosting can remove much of that server maintenance. Flask’s production deployment resources identify services such as PythonAnywhere, Google App Engine, Google Cloud Run, AWS Elastic Beanstalk, and Microsoft Azure as hosting options. The trade-offs are operational control, TLS and patch responsibility, networking complexity, portability, and cost:

Decision factor Self-managed Nginx and Gunicorn Managed Flask/Python hosting
Operational control Full control of Nginx configuration, process users, sockets, firewall, and logs. Provider-defined controls and deployment workflow; low-level access varies.
TLS and patching You select certificates, renew them, and patch the host and proxy. The service may automate certificates and platform patches, subject to its product settings.
Networking You design DNS, listeners, private binds, firewall rules, and any load-balancer chain. Provider networking can simplify ingress but may add platform-specific routing and proxy headers.
Portability Standard Flask, Gunicorn, and Nginx files are easy to move between conventional servers. Deployment conventions and managed services can create migration work.
Cost Depends on the server, bandwidth, storage, and your maintenance time. Depends on the provider’s current plan, requests, runtime, and bandwidth charges; no universal price is established here.

Choose self-management when you need predictable server-level behavior or already operate Linux services. Choose managed hosting when reducing patching and edge-configuration work matters more than controlling every proxy and network detail. In either model, verify how the platform sets forwarded headers before enabling ProxyFix.

Production checklist

  • Gunicorn runs as a dedicated non-root account.
  • Gunicorn listens only on 127.0.0.1:8000, a protected private address, or a restricted Unix socket.
  • Nginx owns the public listeners on 80 and 443.
  • The port-80 block explicitly redirects to HTTPS when clear-text traffic should not serve the API.
  • The port-443 block terminates TLS and contains the proxy configuration.
  • X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, and any needed prefix are forwarded consistently.
  • ProxyFix trusts exactly the proxies in your deployment chain.
  • Internal URLs in upstream Location headers are corrected only when they actually occur.
  • The firewall blocks direct public access to Gunicorn.
  • nginx -t passes before every reload, and Nginx and Gunicorn logs are monitored after changes.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.