Skip to content

Migrating from Apache to Nginx — what actually changes

A real Apache-to-Nginx migration plan — config translation, .htaccess elimination, parity testing, cutover strategy, and the parts that are not 1:1.

Migrating from Apache to Nginx is rarely about Nginx being “faster” — modern Apache with event MPM is competitive on most workloads. The motivation is usually operational: a smaller config surface, no .htaccess, predictable single-threaded worker model, better fit for a microservices-front-edge pattern. This article is the migration runbook we use: audit, translate, test in parallel, cut over with rollback ready, and the gotchas where the two servers do not map 1:1.

How to verify

Before starting, capture the current state of Apache so you can validate the Nginx config produces the same behavior:

sudo apache2ctl -S
sudo apache2ctl -M | sort
find /etc/apache2/sites-enabled -name '*.conf' -exec wc -l {} \;
find /var/www -name '.htaccess' -exec wc -l {} \;
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://example.com/

The vhost list, the active modules, and the .htaccess count tell you the scope. A site with 50 vhosts and 200 .htaccess files is a longer migration than one with 3 vhosts and AllowOverride None.

What’s happening

The two servers solve the same problem with different models:

  • Apache — process/thread per connection (configurable via MPM), dynamic module load, per-directory .htaccess support, request handling pipeline with hooks.
  • Nginx — single master + worker processes, event-driven, fixed module set at compile time (or via dynamic modules), no per-directory config, request handling phases.

Most of an Apache config translates cleanly to Nginx with mechanical substitution:

ApacheNginx
<VirtualHost *:443>server { listen 443 ssl; ... }
ServerName example.comserver_name example.com;
ServerAlias www.example.comserver_name example.com www.example.com;
DocumentRoot /var/www/example.com/publicroot /var/www/example.com/public;
<Directory> + AllowOverride Nonelocation / block with directives
RewriteRule ^/api/(.*) ...rewrite ^/api/(.*) ... or location regex
ProxyPass / http://upstream/proxy_pass http://upstream;
SSLCertificateFile, SSLCertificateKeyFilessl_certificate, ssl_certificate_key
Header set X "y"add_header X "y" always;

Where they differ:

  • .htaccess does not exist in Nginx. Every .htaccess rule must be moved into the server or location block.
  • Rewrite rules are subtly different. Nginx’s rewrite does not chain the same way; the equivalent of [L] is last or break, and the leading-slash convention matches vhost-scope rewrites, not .htaccess.
  • PHP is always FastCGI in Nginx (no equivalent to mod_php). If you ran mod_php, you must move to PHP-FPM first (see Apache + PHP-FPM proxy for the FPM setup that works for both servers).
  • Modules — Nginx ships fewer modules in the binary; some Apache features (mod_security) have Nginx equivalents but require building from source or a dynamic module.

The procedure

The safest migration is a parallel run, not an in-place flip. The pattern:

  1. Audit the Apache config. Document every vhost, every rewrite rule, every .htaccess, every module:

    sudo apache2ctl -S > /root/apache-vhosts.txt
    sudo apache2ctl -M | sort > /root/apache-modules.txt
    find /var/www -name '.htaccess' -exec sh -c 'echo "=== $1 ==="; cat $1' _ {} \; > /root/htaccess-dump.txt

    The .htaccess dump is the migration’s hardest input — every rule needs to be translated and assigned to the right Nginx location block.

  2. Install Nginx on the same box, on a different port. Bind Nginx to port 8443 (or 81/444) so it does not collide with Apache:

    sudo apt install -y nginx
    sudo sed -i 's/listen 80 default_server;/listen 81 default_server;/' /etc/nginx/sites-enabled/default
    sudo systemctl reload nginx
  3. Translate one vhost at a time. Start with the simplest. For an Apache vhost like:

    <VirtualHost *:443>
        ServerName example.com
        DocumentRoot /var/www/example.com/public
        <FilesMatch \.php$>
            SetHandler "proxy:unix:/var/run/php/php8.2-fpm.sock|fcgi://localhost/"
        </FilesMatch>
        <Directory /var/www/example.com/public>
            AllowOverride None
            Require all granted
        </Directory>
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    </VirtualHost>

    The Nginx equivalent (saved to /etc/nginx/sites-available/example.com.conf):

    server {
        listen 8443 ssl http2;
        server_name example.com;
        root /var/www/example.com/public;
        index index.php index.html;
    
        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
        location / {
            try_files $uri $uri/ /index.php?$args;
        }
    
        location ~ \.php$ {
            include fastcgi_params;
            fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_index index.php;
        }
    
        access_log /var/log/nginx/example.com-access.log;
        error_log  /var/log/nginx/example.com-error.log;
    }
  4. Parallel-test each vhost. With Apache on 443 and Nginx on 8443, send identical curl requests to both and diff the responses:

    for path in / /about /api/health /static/style.css; do
      a=$(curl -sk -o /dev/null -w '%{http_code} %{size_download}' https://example.com:443$path)
      n=$(curl -sk -o /dev/null -w '%{http_code} %{size_download}' https://example.com:8443$path -H 'Host: example.com')
      echo "$path  apache=$a  nginx=$n"
    done

    Status code and content length should match. Differences point to translation gaps — usually a rewrite rule or a header that did not get carried over.

  5. Migrate .htaccess rules into the Nginx config. This is where bespoke testing matters. For each .htaccess rule, translate and put in the matching location block. Common patterns:

    # Equivalent of: RewriteCond %{HTTPS} off / RewriteRule .* https://...
    if ($scheme = http) { return 301 https://$host$request_uri; }
    
    # Equivalent of: Deny from all
    location /private { return 403; }
    
    # Equivalent of: <FilesMatch \.(env|git|svn)$> Require all denied
    location ~ /\.(env|git|svn) { deny all; return 404; }
  6. Move ModSecurity if you used it. The Apache + ModSecurity stack maps to Nginx + ModSecurity-nginx (a dynamic module). The rule set is the same; the connector is different. Validate the WAF still fires by sending a test malicious request to both servers and confirming a 403.

  7. Cutover plan.

    • Reduce Apache’s TLS cert TTL — at this point both servers use the same certs.
    • Swap the ports: apache2 to port 8080 (or stop), nginx to port 443.
    • Reload firewall.
    • Watch the logs from both servers; have a one-command rollback ready (systemctl stop nginx && systemctl restart apache2 after swapping listeners back).
  8. Run with Apache stopped but installed for 48 hours. If something breaks that only Apache caught, the rollback is one command. After 48 hours of clean traffic on Nginx, remove Apache:

    sudo apt remove --purge apache2
    sudo apt autoremove

Common pitfalls

  • A site with deep .htaccess tree (WordPress with many plugins, Magento) needs every .htaccess rule audited; missed rules show up as 404s or wrong redirects after cutover.
  • Apache’s mod_rewrite flags [L] and Nginx’s rewrite last do not behave identically — last re-enters the location-matching phase, break does not. Test redirects.
  • mod_proxy_balancer with Apache’s BalancerMember maps to Nginx upstream blocks, but the load balancing algorithms (round-robin, least-conn, ip-hash) have different names.
  • Apache’s SSLUseStapling is Nginx’s ssl_stapling on; ssl_stapling_verify on; resolver ...; — the resolver is required in Nginx and easy to forget.
  • HTTP/2 server push (H2Push in Apache) is gone from both servers as of recent versions — do not migrate this feature; it was deprecated upstream.

Stack Harbor runs Apache-to-Nginx migrations as a defined runbook with parallel-running validation — no big-bang flips, no cutover at 3 a.m. without a rollback. If you have an Apache fleet and the architectural call is to move to Nginx (or vice versa), the migration plan is part of Managed Operations. See also Nginx install for the destination-side baseline.