Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk12 min

How to Fix 502 Bad Gateway on Nginx with WordPress

A 502 on WordPress behind Nginx is usually an upstream PHP-FPM, resource, dependency, or application failure. This guide maps each log signature to a safe fix.

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.

A 502 Bad Gateway on a WordPress site running behind Nginx means Nginx could not obtain a valid response from its upstream, usually PHP-FPM. Start with the Nginx error log, match the failure wording to the PHP-FPM service and listener, then check worker capacity, memory, database or cache dependencies, and any WordPress code limited to the failing URL. Do not begin by increasing timeouts: a missing socket, crashed PHP process, or saturated backend will remain broken until its underlying cause is corrected.

What a 502 means in a WordPress-on-Nginx stack

When a browser requests a PHP-generated WordPress page, Nginx accepts the HTTP request and passes PHP work to an upstream PHP-FPM pool. The hand-off can use a Unix socket file or a TCP listener. PHP-FPM executes WordPress code, talks to the database and any cache service, and sends response headers and content back to Nginx. Nginx then returns the result to the browser.

As an Amazon Associate I earn from qualifying purchases.

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.

The 502 page is generated by Nginx, but it does not identify which downstream component failed. The upstream may be stopped, listening somewhere other than the address Nginx is using, refusing connections, running out of workers or memory, timing out while WordPress waits on a dependency, or closing the connection after a PHP fatal error. The same symptom can therefore require completely different fixes.

A 504 usually indicates that Nginx waited too long for the upstream, while a 502 generally means the connection or response was unusable. The distinction is useful, but the exact error-log line is more valuable than the browser status alone.

#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.

Capture the failure before changing anything

  1. Reproduce once. Record the complete URL, HTTP method, UTC or local time, and whether the problem affects every page or only one route such as /wp-admin, a REST endpoint, or /wp-admin/admin-ajax.php.
  2. Test more than one request. Open a simple static file, the home page, a known PHP page, and the failing URL. A static page working while PHP pages fail points toward the PHP upstream rather than the network listener or Nginx process itself.
  3. Do not repeatedly refresh a failing expensive request. Repeated requests can consume the remaining PHP-FPM workers and make a capacity incident worse. One reproducible request with an exact timestamp is enough to correlate logs.
  4. Keep a rollback copy. Before editing an Nginx or PHP-FPM file, copy the file and note the original path. A configuration change that passes a syntax check can still alter routing, so retain a quick way back.

Read the Nginx error log first

Nginx’s error-log path depends on the installation. A common Linux path is /var/log/nginx/error.log; virtual-host or package-specific configurations may send errors elsewhere. Check the active Nginx configuration if that file is empty, then inspect entries surrounding the reproduction time:

sudo tail -n 100 /var/log/nginx/error.log

Correlate the Nginx line with the PHP-FPM log at the same second. Nginx documents upstream timing variables including $upstream_connect_time, $upstream_header_time, $upstream_response_time, and $request_time. If your access-log format records them, they show whether the delay occurred while connecting, waiting for headers, receiving the response, or processing the whole request. A zero connect or header value can mean the upstream was never reached or that a complete header was not received; interpret it with the error-log wording rather than in isolation.

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

Use the log signature to choose the next check

Log wording or symptom Most likely area First action
connect() failed, No such file or directory, or Connection refused PHP-FPM is stopped, the socket or port is wrong, or permissions prevent Nginx from connecting. Check the PHP-FPM service, its listen value, the socket or TCP port, and Nginx’s fastcgi_pass.
upstream timed out PHP-FPM is slow or saturated, or WordPress is waiting on a database, cache, external call, or long-running task. Check worker utilization, memory pressure, dependency latency, and the specific URL before changing a timeout.
upstream sent too big header The upstream response headers exceed Nginx’s configured buffers, often because of large cookies or application-generated headers. Identify the response and its headers; reduce unnecessary cookies or headers before sizing buffers deliberately.
upstream prematurely closed connection PHP-FPM or PHP code crashed, hit a fatal error, was killed, or was terminated while producing the response. Inspect PHP-FPM and PHP application logs, kernel out-of-memory messages, and recent code or configuration changes.
Only one WordPress route fails A plugin, theme callback, scheduled task, or request-specific data path may be broken. Isolate that route and roll back the most recent WordPress change in a controlled manner.

Verify PHP-FPM is running and listening where Nginx expects

The most important configuration rule is exact agreement: the PHP-FPM pool’s listen directive and Nginx’s fastcgi_pass target must refer to the same Unix socket or the same TCP address and port. A nearly identical path is still a mismatch.

  1. Find the PHP-FPM unit. List services and identify the unit used by this site:
systemctl list-units --type=service | grep -Ei 'php.*fpm|fpm.*php'

Run sudo systemctl status with the exact unit name shown. If it is inactive or repeatedly restarting, read its recent journal and PHP-FPM log before attempting another restart.

  1. Inspect the pool listener. Pool files vary by distribution. Search the usual PHP configuration directories:
sudo grep -R "^[[:space:]]*listen[[:space:]]*=" /etc/php /etc/php-fpm.d 2>/dev/null

The result may be a path such as /run/php/php8.2-fpm.sock or a TCP value such as 127.0.0.1:9000. Use the value from the pool serving this WordPress installation, not a socket belonging to another PHP version or pool.

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.
  1. Confirm the endpoint exists. For a Unix socket, list sockets under /run:
sudo find /run -type s | grep -E 'php.*fpm|php.*sock'

For a TCP listener, check listening ports with ss -ltnp and confirm the address and port match the pool. If the pool is configured for a socket that does not exist, PHP-FPM may not have started, may have failed to create it, or may be using a different pool file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Check permissions. Nginx’s worker user must be able to access a Unix socket. Inspect its mode, owner, and group:
stat -c '%A %U %G %n' /run/php/php8.2-fpm.sock

Use the actual socket path reported by your pool. Compare the socket group and mode with the Nginx worker user configured on the server. Correct the pool’s socket ownership or permissions through the PHP-FPM configuration rather than granting broad access to the entire runtime directory.

  1. Compare Nginx’s target. Search the active server configuration for fastcgi_pass:
sudo nginx -T 2>/dev/null | grep -n fastcgi_pass

If the pool says listen = /run/php/php8.2-fpm.sock, the corresponding Nginx line must be fastcgi_pass unix:/run/php/php8.2-fpm.sock;. If the pool says 127.0.0.1:9000, Nginx must use fastcgi_pass 127.0.0.1:9000;. Do not mix a Unix-socket value with a TCP form.

Fix a missing socket, refused connection, or stopped PHP-FPM

When the log reports a missing socket or refused connection, increasing fastcgi_read_timeout cannot help because Nginx has no usable upstream connection. Check for a failed package upgrade, a PHP version change that left an old socket in the site configuration, a disabled pool, or a service that is restarting because of a syntax or resource error.

  • Use the service status and recent journal output to identify why PHP-FPM is not staying up.
  • Make listen and fastcgi_pass agree exactly, including the PHP version in a socket filename.
  • Check that the socket directory exists and that the service account can create the socket.
  • After correcting the cause, restart or start the PHP-FPM unit using your distribution’s normal service manager, then verify that the socket or port appears.
  • Validate Nginx with sudo nginx -t before reloading it. A successful test means the syntax is valid; it does not replace checking the listener and making one controlled request.

Handle an upstream timeout without hiding the cause

An upstream timed out entry means the request spent too long waiting at some stage of the PHP exchange. Common causes are all PHP-FPM workers being busy, a request that performs expensive WordPress work, database lock or query latency, an unavailable cache service, memory pressure, or a process stuck on an external dependency.

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

Check PHP-FPM capacity

Review the pool’s process-manager settings, including its maximum worker count, spare-server limits, and whether workers are repeatedly being recycled. Compare the number of active requests with available memory: raising the worker limit can increase concurrency but can also trigger swapping or the kernel out-of-memory killer. Look for worker-limit warnings and restarts in the PHP-FPM log.

Check host memory and process pressure

Inspect RAM, swap activity, load, and the kernel log around the failure. A worker killed for memory can appear in Nginx as a timeout or a prematurely closed connection. Freeing memory, correcting an unexpectedly large request, or reducing concurrency is safer than adding a larger timeout to a host that cannot complete the work.

Check database and cache dependencies

WordPress may be healthy enough to accept a request but unable to finish because MySQL or a Valkey/Redis service is slow, unavailable, or refusing connections. Correlate database errors and latency with the same timestamp. A cache outage can affect login, admin, REST, or AJAX requests differently from ordinary page views, so test the URL that actually failed.

Change a timeout only after measuring the workload

If logs show that a legitimate operation consistently completes just beyond the current limit and PHP-FPM, memory, database, and cache capacity are healthy, increase the relevant FastCGI timeout cautiously. Base the value on observed completion time plus a margin, apply it only to the necessary location when possible, and monitor the resulting worker occupancy. A larger timeout for a dead or saturated backend merely keeps connections open longer and can exhaust Nginx or PHP-FPM capacity.

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

Resolve an oversized upstream header

The upstream sent too big header signature means Nginx could not fit the upstream response headers into its configured buffers. WordPress plugins, authentication flows, tracking systems, and unusually large cookies can produce this condition.

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.
  1. Identify the exact URL and account or cookie state that triggers the response.
  2. Test in a private browser session and with cookies cleared to determine whether the header size is request-specific.
  3. Inspect recent plugin, theme, login, redirect, and cookie changes. Remove redundant or oversized headers where possible.
  4. If the header is legitimate and unavoidable, size the FastCGI header buffers deliberately in the affected server or location, validate with nginx -t, and retest. Avoid applying a very large global buffer as a substitute for finding a runaway header.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Investigate a prematurely closed connection

When PHP-FPM closes the connection before Nginx receives a complete response, inspect PHP-FPM’s log, the PHP error log, and the kernel log for fatal errors, segmentation faults, worker termination, execution limits, or out-of-memory kills. Compare the first failing request with any recent PHP version, extension, plugin, theme, or configuration change.

Restarting PHP-FPM can clear a wedged worker, but it is a recovery action, not a diagnosis. If the same URL crashes a fresh worker, isolate the application code or input that triggers it before restarting repeatedly. Preserve the timestamp and error details so a code change can be tied to the failure.

Isolate WordPress-only failures

If the home page works but /wp-admin, REST, or admin-ajax.php returns 502, the Nginx-to-PHP-FPM connection may be healthy and the failing path may be executing different WordPress code.

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

Compare request scope

  • Every PHP URL fails: return to PHP-FPM state, listener agreement, socket permissions, and host resources.
  • Only administration fails: check administrator-only plugins, dashboard widgets, scheduled jobs, authentication cookies, and database queries used by the dashboard.
  • Only REST or AJAX fails: inspect the plugin or theme callback attached to that route and the request payload. A long-running AJAX action can consume workers even when ordinary pages remain fast.
  • Only one public URL fails: check the template, shortcode, query, or content item used by that URL.

Roll back the most recent WordPress change safely

Use a maintenance window and preserve a backup. If the dashboard is available, deactivate the newest suspect plugin or switch temporarily to a known-good theme from the WordPress administration screens. If the dashboard itself is unavailable, run WP-CLI from the WordPress installation directory; for example, wp plugin deactivate --all is a broad isolation test, while wp plugin deactivate plugin-slug targets one known plugin. Reactivate components one at a time and retest so the offending change is identifiable.

When WP-CLI is not available, rename the suspected plugin directory through the server’s file-management method, test once, and restore the original name after the test. Do not leave all plugins disabled as a permanent fix. Also review scheduled tasks and recent automated jobs: a cron task that runs expensive work can make an administrator request appear to be the source of a timeout when it is actually competing for the same PHP-FPM workers.

Validate and reload Nginx without making the outage worse

  1. Back up every Nginx file you changed, including the site server block and any included FastCGI configuration.
  2. Run sudo nginx -t. Do not reload if the test reports an error.
  3. If the test passes, reload rather than stopping Nginx: sudo systemctl reload nginx.
  4. Make one controlled request to the previously failing URL and immediately check the error and PHP-FPM logs.
  5. If the behavior worsens, restore the backup, run sudo nginx -t again, reload, and continue investigating the original upstream condition.

A configuration test checks syntax and referenced files; it does not prove that PHP-FPM is running, that a socket is reachable, or that WordPress can complete its database work.

Use Nginx debug logging only as a short escalation

Nginx debug logging is disabled by default and requires an Nginx build compiled with debug support. Check the build flags with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
nginx -V 2>&1 | grep -- --with-debug

If debug support is present, temporarily set the relevant error-log directive to error_log /var/log/nginx/error.log debug;, run one controlled reproduction, and capture the resulting entries. Debug logs can grow very large and affect performance, so enable them only long enough to answer a specific question. Run nginx -t before reloading, then restore the previous log level and reload again. If the build lacks debug support, rely on ordinary error and access logs plus PHP-FPM and system logs instead.

A practical decision checklist

Question Yes: next move No: next move
Does the error log name a missing socket or refused connection? Check PHP-FPM service state, pool listener, socket creation, permissions, and the exact fastcgi_pass target. Continue to the timing or response-signature checks.
Are only one or two WordPress endpoints failing? Isolate the plugin, theme, scheduled task, query, or request payload used by those endpoints. Assess PHP-FPM and host-wide capacity.
Are all workers busy or being killed? Measure memory, worker limits, request duration, and dependency latency; reduce load or correct the resource fault. Inspect database, cache, PHP errors, and recent application changes.
Does the log say the upstream sent too large a header? Find the oversized cookie or response header; reduce it or adjust buffers only when justified. Follow the exact wording of the error instead of changing unrelated settings.
Did a configuration change just precede the outage? Restore the known-good copy, validate with nginx -t, reload, and reapply one change at a time. Correlate service, application, and dependency logs by timestamp.

Prevent the next 502

  • Keep Nginx, PHP-FPM, WordPress, plugins, and themes under change control, with a tested rollback for each production update.
  • Monitor PHP-FPM restarts, worker saturation, memory pressure, database latency, and cache availability rather than monitoring only the HTTP status code.
  • Retain enough Nginx and PHP-FPM log history to correlate an incident by timestamp.
  • Test administrator, REST, AJAX, and representative public pages after PHP or WordPress changes; they do not exercise identical code paths.
  • Document the active PHP-FPM pool, its listen value, the matching Nginx fastcgi_pass, socket permissions, and service-unit name.
  • Use debug logging only for a short, measured investigation and return to the prior log level afterward.

The reliable remedy is the one that matches the evidence: repair the listener for a connection error, investigate workload and dependencies for a timeout, correct headers for a buffer error, and isolate crashing WordPress code for a premature close. Nginx reports the gateway failure; the correlated upstream and application logs identify what actually needs fixing.

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.