Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Apache

How to Migrate from Apache to Nginx on an Ubuntu VPS

By Freedom251 Team · · 10 min read

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

The safest Apache-to-Nginx migration is staged: inventory Apache, install Nginx without taking over its ports, translate each VirtualHost into a Nginx server block, test HTTP routing, then add HTTPS and move production traffic. If the application is not ready to leave Apache, run Apache on an internal port and let Nginx reverse proxy to it. Keep the old configuration and a tested reversal procedure until hostnames, application routes, uploads, logs, IPv4/IPv6 access, and certificate renewal all work.

Choose a migration strategy before changing the server

There are two practical ways to move a site. A full replacement makes Nginx the web server for every hostname and eventually stops Apache. A staged migration puts Nginx in front while Apache continues serving the application on a private listener. The second option lets you validate routing and TLS with a quick rollback, but it adds proxy headers, another process, and more places for timeouts or body-size limits to differ.

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.
Decision point Full replacement Staged reverse proxy
Cutover risk Higher: every translated rule must work when traffic moves. Lower: Apache remains available behind Nginx while you test.
Rollback speed Requires restoring Apache to ports 80 and 443. Usually a port or service reversal, provided the Apache listener and configuration remain intact.
Configuration complexity Simpler final stack after the migration. More complex because proxy headers, buffering, limits, and timeouts must be managed.
Application compatibility Requires translating PHP handlers, rewrites, authentication, and proxy rules. Preserves Apache behavior while Nginx handles the edge.
TLS ownership Nginx terminates HTTPS directly. Nginx normally terminates HTTPS and forwards the request to Apache.
Observability One access and error-log layer. Inspect both Nginx and Apache logs, and correlate request IDs if the application supplies them.

For a small static site, a direct replacement is usually straightforward. For a stateful application, a staged proxy is safer until login sessions, uploads, background callbacks, and unusual URL routes have been exercised.

Inventory Apache and create a rollback checkpoint

Do not start by editing Nginx. First record what Apache is actually doing, including settings that may be hidden in included files or enabled modules.

#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.
  • List every enabled site and its ServerName and ServerAlias values.
  • Record each document root, index-file order, symbolic link, and filesystem ownership.
  • Map PHP, Python, Node.js, or other application handlers, including their sockets or ports.
  • Copy every rewrite, redirect, authentication rule, access restriction, custom header, compression rule, and upload limit.
  • Record reverse-proxy destinations, WebSocket paths, health-check endpoints, and any URL exceptions.
  • Save certificate and key paths, renewal hooks, cron jobs, systemd units, firewall rules, and DNS records.
  • Back up /etc/apache2/, the application code, uploaded files, and the database before changing listeners.

Use this inventory as the change-control checkpoint. A Nginx configuration is not a textual copy of an Apache VirtualHost: directive names, matching order, rewrite syntax, access controls, and application handlers differ. Mark each Apache behavior as translated, intentionally removed, or still provided by Apache.

Install Nginx and avoid a port collision

Ubuntu distributes Nginx as a package and manages it with systemd. With an administrative shell, install it and inspect the service:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo apt update
sudo apt install nginx
sudo systemctl status nginx

A newly installed service normally attempts to listen on ports 80 and 443. If Apache already owns either port, Nginx cannot bind to it. Before starting or enabling the new site, choose one of these arrangements:

  • Stop Apache during a planned cutover, then start or reload Nginx.
  • Move Apache to an internal address such as 127.0.0.1:8080 for a staged proxy migration.
  • Temporarily use a test address or isolated port while validating the configuration.

Do not expose an internal Apache listener on a public interface unless there is a specific reason and a firewall rule protecting it. Confirm listeners with your operating system’s socket tools and make sure only the intended edge service answers publicly.

Translate an Apache VirtualHost into a Nginx server block

Nginx keeps site files in /etc/nginx/sites-available/ and enables them through symbolic links in /etc/nginx/sites-enabled/. Create one file per hostname group. The following is a minimal static-site equivalent for an Apache host serving files from /srv/example.com/public:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /srv/example.com/public;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}

The two listen lines cover IPv4 and IPv6. The server_name list must match the DNS names that clients send. Keep names unique across enabled server blocks; an accidental duplicate can send traffic to the wrong default block. Set root to the directory that contains the public files, not the application directory that holds secrets or configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Enable the site and remove the default only when appropriate

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl reload nginx

Remove the default link only if it is no longer needed for another hostname, a maintenance page, or an emergency fallback. The configuration test must succeed before every reload. A reload applies the new workers without needlessly terminating existing connections; a failed test leaves the running configuration in place.

Translate common VirtualHost concepts deliberately

Apache concept Nginx approach Migration check
ServerName and ServerAlias One server_name directive containing every intended hostname. Check DNS, certificate names, and canonical redirects for each name.
DocumentRoot root at server or location scope. Verify that the Nginx worker can traverse directories and read files.
DirectoryIndex index directive. Request the bare directory and confirm the intended index file.
mod_rewrite rules rewrite, return, or try_files, depending on the rule. Test both matching and non-matching paths; do not paste Apache regular expressions unchanged.
ProxyPass location with proxy_pass and explicit forwarding headers. Check host, client-IP, scheme, WebSockets, timeouts, and request-body size.
.htaccess No per-directory equivalent is read automatically. Move every required rule into the server configuration and deploy it centrally.

Apache’s directory and access-control semantics do not carry over automatically. If the old site depended on .htaccess, inspect every directory for redirects, authentication, caching, or denial rules before declaring the translation complete.

Serve static files directly or proxy Apache

Direct static serving

Use root, index, and try_files when Nginx should deliver files itself. The try_files pattern prevents arbitrary path fall-through and returns a 404 for a missing object. For a single-page application, the required fallback may instead be the application’s entry point; make that a deliberate rule rather than assuming every missing path is a file.

Run Apache behind Nginx during a staged migration

Move Apache to an internal listener such as 127.0.0.1:8080, then use a Nginx server block like this:

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.
server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

These headers preserve the public hostname, client address, proxy chain, and original scheme for applications that understand forwarded requests. Configure the application to trust them only from your Nginx proxy; otherwise a client could forge a secure-scheme or client-IP value.

Test application-specific behavior instead of copying a generic proxy block blindly. WebSockets may need an HTTP/1.1 upgrade configuration. Large uploads require compatible client and upstream body limits. Streaming responses can be affected by buffering. Long reports or imports may need longer proxy timeouts. PHP can remain behind Apache during this stage, or be moved to PHP-FPM later, but do not change both the web server and application handler without a separate test.

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

Make HTTP routing work before adding HTTPS

Use a temporary hosts-file entry, a staging hostname, or controlled DNS to test the Nginx server block before changing public traffic. For every hostname, verify:

  • The expected server block answers rather than the default site.
  • The canonical hostname redirect is intentional and does not loop.
  • Static assets, directory indexes, robots files, and application routes return the expected status.
  • Login, session cookies, CSRF checks, callbacks, uploads, downloads, and large responses work.
  • Both IPv4 and IPv6 reach the same service if an AAAA record exists.
  • Nginx access and error logs show the request and contain no permission, upstream, or rewrite errors.

Only after HTTP behavior is correct should you redirect port 80 to HTTPS and configure the TLS listener. Separating routing from encryption makes failures easier to identify.

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

Keep HTTPS working with Nginx and Certbot

For an existing certificate, copy or reference the correct certificate and private-key files in a port-443 server block, then test the configuration before reloading. Do not copy a private key into a world-readable application directory. Ensure the server_name values in the TLS block match the names users request.

For a new or replacement certificate, Certbot’s Nginx flow can find the matching server block, obtain a certificate, write the TLS directives, reload Nginx, and install a renewal timer. The documented commands are:

sudo snap install --classic certbot
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run
sudo systemctl status snap.certbot.renew.timer

The HTTP-01 validation method requires the public hostname to reach port 80. Keep the port-80 server available for the challenge and for redirecting ordinary requests. If DNS still points at the old server, a firewall blocks port 80, or another service answers the challenge path, issuance will fail.

After issuance, inspect the generated Nginx configuration rather than assuming every redirect is correct. A common final shape has a port-80 block that returns a permanent redirect to the same URI on HTTPS and a port-443 block containing the certificate, key, and application location. Run sudo nginx -t before reloading. Renewal is attempted automatically twice daily by the installed timer, but a successful dry run and an observed timer status are stronger checks than merely trusting the schedule.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate the cutover systematically

When DNS or the load balancer points at Nginx, test each hostname from outside the VPS as well as locally. Record the result of every check so a later rollback has a known baseline.

  1. Run sudo nginx -t and reload with sudo systemctl reload nginx.
  2. Request HTTP and HTTPS for every server_name; confirm status codes, redirects, and the final canonical URL.
  3. Open representative pages and API endpoints, then test login, logout, session persistence, password reset, and third-party callbacks.
  4. Upload and download files at the largest supported size; check filename handling and permissions.
  5. Exercise cache-control, compression, streaming, WebSocket, and long-running endpoints if the application uses them.
  6. Inspect Nginx access and error logs and, for a proxy setup, the Apache logs for matching timestamps and status codes.
  7. Test from an IPv4-only network and an IPv6-capable network. An AAAA record that reaches the old service can make a migration appear randomly broken.
  8. Run sudo certbot renew --dry-run and confirm sudo systemctl status snap.certbot.renew.timer reports the expected timer.

Watch for differences that basic page loads miss: absolute URLs generated with http, cookies lacking the Secure attribute, incorrect client IPs in audit logs, 413 errors on uploads, 502 or 504 proxy responses, and rewrite loops caused by an application that does not understand X-Forwarded-Proto.

Keep a documented rollback path

Do not decommission Apache immediately after a successful homepage check. Keep the saved configuration, database and upload backups, package versions, DNS values, and the exact reversal commands accessible to the operator who will be on call.

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

For a staged migration, rollback can mean changing Nginx to serve a maintenance response or restoring the previous proxy target while Apache remains on its internal port. For a full replacement, the reversal normally requires stopping Nginx, returning Apache to ports 80 and 443, restoring its enabled VirtualHosts, testing Apache’s configuration, and reloading it. Coordinate DNS changes and low TTLs in advance; DNS caches can keep some visitors on the old address after a switch.

Keep the rollback option until all hostnames, routes, uploads, logs, IPv4/IPv6 paths, and renewal checks have passed during a representative operating period. Once Apache is no longer needed, remove its public listeners, disable unused modules and services, and retain an archived configuration for audit or emergency recovery.

Troubleshoot the failures that appear most often

Nginx will not start or reload

Run sudo nginx -t first. Syntax errors, duplicate directives, missing semicolons, broken include paths, and duplicate server names are common causes. If the test passes but the service cannot bind, another process still owns port 80 or 443; resolve the listener conflict before changing unrelated configuration.

The wrong site or certificate appears

Check that the intended symlink exists in /etc/nginx/sites-enabled/, the requested hostname is present in server_name, and DNS reaches this VPS over both address families. A default server or duplicate name can win when the Host header does not match as expected. Confirm that the certificate’s names cover the exact hostname, including the www variant when used.

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

The proxy returns 502 or 504

Confirm Apache is listening on the address and port in proxy_pass and that a local firewall is not blocking it. Read the Nginx error log and Apache log together. A 502 commonly indicates connection refusal or an invalid upstream response; a 504 usually points to an application timeout, overloaded worker, or an operation that needs an intentionally longer timeout.

HTTPS redirects loop or the application thinks requests are HTTP

Ensure the proxy sends X-Forwarded-Proto $scheme and that the application trusts the proxy’s forwarded headers. Remove competing HTTP-to-HTTPS rules in Apache or the application until one layer owns the canonical redirect. Test a request that begins on HTTP and follow every redirect to its final URL.

Files return 403 or uploads fail

Check directory execute permission, file read permission, the Nginx worker’s user, and any mandatory access-control policy. For uploads, compare Nginx’s request-body limit with Apache, the application framework, and PHP or another runtime. A successful small upload does not prove that the production limit is sufficient.

After migration: operate the new edge deliberately

Keep server blocks in source control or another audited backup, document which service owns each port, and monitor certificate expiry, renewal logs, disk space, error rates, upstream latency, and IPv6 reachability. Review Nginx and application logs after deployment rather than deleting them during cleanup. Remove only Apache modules, listeners, and packages that are no longer required, and do so after the rollback window closes.

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.

The migration is complete when Nginx serves every intended hostname, the application receives correct host and client-protocol information, HTTPS renews without intervention, and you can explain exactly how to restore service if a future configuration change fails.

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.

ApacheCertbotHTTPSNGINXserver administrationUbuntuVPS

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.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.