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.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
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.
How the public URL reaches Flask
A production request normally follows this path:
- The client requests
http://SERVER_IP,http://SERVER_IP:80, or a hostname such asapi.example.com. - Nginx accepts the public connection on port 80 or 443.
- For an HTTPS request, Nginx terminates TLS and decrypts the HTTP request.
- Nginx forwards the request over the loopback interface to Gunicorn at
127.0.0.1:8000, or through a Unix socket. - 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
- [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:8000or 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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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
- 【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.
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.
Rank #3
- [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.
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
- 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:
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →- 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.Validate, reload, and observe the deployment
- Run
nginx -tand correct every reported syntax, include, certificate-path, or permission error. - Reload Nginx through your service manager only after the test succeeds. A reload applies the new configuration without requiring a full stop.
- Request the public HTTP URL and verify that the response is a redirect when you configured the port-80 redirect block.
- Request the HTTPS URL and verify that the response is produced by Flask rather than an Nginx default page.
- 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.
- 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.
Best Value
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.
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.
Quick Recap
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
Locationheaders are corrected only when they actually occur. - The firewall blocks direct public access to Gunicorn.
nginx -tpasses 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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute




