Anasayfa / Software / Migrate Your Website from Apache to Nginx: A Step‑by‑Step Guide

Migrate Your Website from Apache to Nginx: A Step‑by‑Step Guide

server migration

Switching from Apache to Nginx can boost performance, reduce memory usage, and give you more control over request handling. While the two servers share many concepts, the configuration syntax is different enough to merit a careful, systematic migration. This guide walks you through every stage – from backing up your current setup to validating the new Nginx configuration – with real commands, common pitfalls, and handy tips for an intermediate‑level sysadmin.

What You’ll Need

  • A Linux server (Ubuntu, Debian, CentOS, or similar) running Apache.
  • Root or sudo privileges.
  • Access to the server via SSH.
  • The website’s source files and any custom .htaccess rules.
  • A basic understanding of Linux command‑line tools.

Step 1: Take a Full Backup

Before you touch anything, create a snapshot of your Apache configuration and website files. This protects you from accidental data loss and gives you a clean rollback point.

sudo mkdir -p /backup/apache_migration
sudo cp -a /etc/apache2 /backup/apache_migration/apache_conf
sudo cp -a /var/www/html /backup/apache_migration/www_html
sudo tar -czf /backup/apache_migration.tar.gz -C /backup apache_migration

If you use a version‑controlled deployment pipeline, tag the current release in Git as well.

Step 2: Install Nginx

Install Nginx from your distribution’s repository. On Ubuntu/Debian you can use apt, while CentOS/RHEL uses yum or dnf.

# Ubuntu/Debian
sudo apt update && sudo apt install -y nginx
# CentOS 7
sudo yum install -y epel-release && sudo yum install -y nginx
# CentOS 8 / RHEL 8
sudo dnf install -y nginx

After installation, start and enable the service so it launches on boot.

sudo systemctl start nginx
sudo systemctl enable nginx

Step 3: Disable Apache Temporarily

To avoid port conflicts, stop Apache while you test Nginx. You can keep it installed for a quick fallback.

sudo systemctl stop apache2   # Ubuntu/Debian
sudo systemctl stop httpd     # CentOS/RHEL

Confirm that nothing is listening on port 80:

sudo ss -tlnp | grep :80

If the output is empty, you’re ready to hand traffic to Nginx.

Step 4: Translate .htaccess Rules to Nginx

Apache’s .htaccess files are powerful but Nginx does not read them. You’ll need to convert the most common directives (rewrites, redirects, security headers, etc.) into the nginx.conf or site‑specific files.

Here are three typical conversions:

# Apache rewrite (in .htaccess)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

# Equivalent Nginx location block
location / {
    try_files $uri $uri/ /index.php?q=$uri&$args;
}

# Apache redirect
Redirect 301 /old-page.html https://example.com/new-page.html

# Nginx redirect
rewrite ^/old-page.html$ https://example.com/new-page.html permanent;

# Apache security header
Header set X-Content-Type-Options "nosniff"

# Nginx header
add_header X-Content-Type-Options "nosniff" always;

Place the converted blocks inside the appropriate server block (usually under /etc/nginx/sites-available/yourdomain).

Step 5: Create an Nginx Server Block

Server blocks in Nginx are analogous to Apache virtual hosts. Create a new file for your domain, then enable it with a symbolic link.

sudo nano /etc/nginx/sites-available/example.com

Paste the following template and adjust paths, domain name, and PHP handling as needed:

server {
    listen 80;
    server_name www.example.com example.com;

    root /var/www/html;
    index index.php index.html index.htm;

    # Logging (optional but helpful during migration)
    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;

    # Basic security headers
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Main request handling
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # PHP processing (PHP-FPM assumed)
    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Adjust version if needed
    }

    # Deny access to hidden files like .htaccess
    location ~ /. {
        deny all;
        access_log off;
        log_not_found off;
    }
}

Save the file, then enable it:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

Test the configuration syntax:

sudo nginx -t

If the test reports syntax is ok and test is successful, reload Nginx.

sudo systemctl reload nginx

Step 6: Verify PHP and Application Functionality

Most dynamic sites rely on PHP‑FPM. Ensure the PHP socket path matches your distribution. On Ubuntu 22.04 the default is /var/run/php/php8.1-fpm.sock. Adjust the fastcgi_pass line accordingly.

Run a quick curl test against a known PHP page:

curl -I http://localhost/info.php

If you get a 200 OK and the PHP info page renders, the back‑end is working. Remember to delete info.php after testing for security.

Step 7: Switch DNS or Load Balancer (Optional)

If your server sits behind a load balancer or you use DNS‑based traffic routing, update the target to point at the same IP (the IP hasn’t changed) – the only difference is the web server listening on port 80. In most cases you can simply start serving traffic now because Nginx is already bound to port 80.

Before you announce the change publicly, run a local sanity check:

curl -s http://localhost | grep -i "welcome"

Look for expected content, missing assets, or 404 errors that indicate a mis‑matched root path.

Step 8: Decommission Apache (Optional)

Once you’re confident Nginx handles all requests correctly, you can uninstall Apache to free up resources.

# Ubuntu/Debian
sudo apt purge -y apache2 && sudo apt autoremove -y
# CentOS/RHEL
sudo yum remove -y httpd

If you prefer to keep Apache as a fallback, simply leave it stopped and disabled:

sudo systemctl disable apache2   # Ubuntu/Debian
sudo systemctl disable httpd     # CentOS/RHEL

Common Mistakes to Avoid

1. Leaving Apache running on port 80. Nginx will fail to bind and the migration stops dead in its tracks. Always stop Apache before testing.

2. Copy‑pasting .htaccess rules without conversion. Nginx ignores .htaccess, so unconverted directives silently disappear, often breaking rewrites or security headers.

3. Mismatching the document root. A common typo is /var/www/html/ vs /var/www/html. The trailing slash can cause try_files to look in the wrong directory.

4. Forgetting to adjust PHP‑FPM socket version. Using the wrong socket path results in a 502 Bad Gateway error.

5. Neglecting to test SSL configuration. If you terminate TLS at Nginx, you must recreate listen 443 ssl blocks and import certificates.

Tips and Tricks

• Use nginx -T for a full dump of the effective configuration. This helps you spot duplicated directives coming from conf.d includes.

• Enable access_log temporarily. Detailed logs make it easier to spot missing assets during the first few days after migration.

• Leverage map and geo blocks. They let you implement conditional redirects or rate‑limiting without cluttering the main server block.

• Take advantage of Nginx’s built‑in caching. Adding proxy_cache_path and proxy_cache directives can dramatically improve performance for API‑backed sites.

• Run a dry‑run with curl -I on every major URL. A short script that loops through a sitemap can reveal 404s before real users encounter them.

Frequently Asked Questions

Will my .htaccess files be ignored completely?

Yes. Nginx never reads .htaccess. All rules must be manually translated into the Nginx configuration. If you have many custom rules, consider using a conversion tool like htaccess2nginx as a starting point, then fine‑tune the output.

Do I need to reinstall my SSL certificates?

No. The certificates are stored as files (e.g., /etc/ssl/certs/…) and can be referenced in the new server block with ssl_certificate and ssl_certificate_key. Just copy the same paths into the Nginx config.

Can I run Apache and Nginx side‑by‑side?

Technically, yes, if they listen on different ports or IP addresses. Some administrators keep Apache for legacy CGI scripts while Nginx acts as a reverse proxy. For a clean migration, however, it’s simpler to run only Nginx.

Conclusion

Migrating from Apache to Nginx is a rewarding project that gives you a leaner, faster web stack. By backing up first, translating .htaccess rules, creating a proper server block, and testing each component, you can switch over with minimal downtime. Keep an eye on logs, avoid the common pitfalls listed above, and you’ll enjoy the performance and scalability benefits of Nginx in no time.

Photo by Kevin Ache on Unsplash

Etiketlendi: