If you move a site from Apache to Nginx, the first thing that breaks is usually the file you never thought much about: .htaccess. Apache reads that file on every request and applies its rules on the spot. Nginx never reads it at all. To convert .htaccess to Nginx, you translate each rule by hand into a server block, test it, and only then switch traffic over.
This guide works through the translation rule by rule: redirects, rewrites, password protection, caching headers, and access blocks, using examples from a real WordPress or PHP site. If you are still weighing the two servers, the comparison of Apache and Nginx for WordPress hosting sets out where each one fits before you commit to a move.
Why .htaccess Rules Do Not Work in Nginx
Apache and Nginx handle requests in different ways, and the difference decides how you convert .htaccess to Nginx. Apache checks directories from the top down and lets a .htaccess file in any folder override the main config. Nginx reads its config once at startup, matches each request against location blocks, and serves it. There is no per-directory override, and no file Nginx picks up at request time.
| Apache concept | Nginx equivalent | What changes |
|---|---|---|
.htaccess in a folder |
Location block in a server block | One config file, applied at startup |
RewriteRule |
rewrite or try_files |
Similar syntax, different matching |
Redirect |
return 301 |
Simpler and faster, no regex needed for plain moves |
AuthType Basic |
auth_basic |
Same password file format, different directives |
Header set |
add_header |
Headers attach to a location, not a folder |
Order allow,deny |
allow / deny |
Same idea, clearer syntax |
One warning before you start: an htaccess to nginx converter tool can draft the translation for you, and the better ones handle plain redirects and rewrites well. Treat the output as a first draft, not a finished config. Converters guess at intent, and a wrong guess on a rewrite can send real traffic to the wrong page or into a redirect loop. Read every line it produces.
How to Convert .htaccess to Nginx, Rule by Rule
Sort each rule into one of five groups: redirects, rewrites, access control, authentication, and headers or caching. Convert one group at a time, and test after each group instead of pasting a whole file and hoping.
Redirects: use return, not rewrite
Plain redirects are the easiest win. Apache writes them like this:
Redirect 301 /old-page/ /new-page/
Redirect 301 /blog/old-post/ https://example.com/blog/new-post/
Nginx does the same job with return, which stops processing the request right there:
location = /old-page/ {
return 301 /new-page/;
}
location = /blog/old-post/ {
return 301 https://example.com/blog/new-post/;
}
For a whole-domain move, one line covers every URL:
server {
listen 80;
server_name old-domain.com www.old-domain.com;
return 301 https://new-domain.com$request_uri;
}
Keep the $request_uri part. Without it, every old link lands on the new homepage instead of its matching page.
Rewrites: translate RewriteRule to nginx rewrite rules
Rewrites cause the most confusion, because Apache rewrite rules and nginx rewrite rules look alike but behave differently. Apache matches against the path without the leading slash and processes rules in order until one matches with the [L] flag. Nginx matches against the full URI, including the leading slash, and its rewrite directive runs inside the location that matched.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
The two conditions say: only rewrite when the requested file and folder do not exist. Nginx expresses that same idea more directly with try_files, and for WordPress or a PHP app this is the form to use instead of a rewrite:
location / {
try_files $uri $uri/ /index.php?$args;
}
That one line replaces the whole Apache block for most sites. It tries the real file, then the real folder, then hands the request to index.php with the query string intact.
When you do need a regex rewrite, the translation is close to literal. Apache:
RewriteRule ^products/([0-9]+)/?$ /product.php?id=$1 [L]
Nginx:
rewrite ^/products/([0-9]+)/?$ /product.php?id=$1 last;
Notice the leading slash in the Nginx pattern, and last where Apache used [L]. The last flag restarts matching with the new URI, which is what you want for an internal rewrite. Use permanent instead when the rewrite should tell browsers and search engines the move is final, which is the same as a 301. One more Apache habit to drop: RewriteBase. Nginx has no equivalent because its rewrites always work from the server root, so fold any base prefix into the pattern itself.
Password protection: auth_basic with the same file
Apache basic auth and Nginx basic auth share the same password file format, so you can often reuse the .htpasswd file unchanged. Apache:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/www/.htpasswd
Require valid-user
Nginx:
location /admin/ {
auth_basic "Restricted Area";
auth_basic_user_file /var/www/.htpasswd;
}
Move the password file outside the web root if it is not there already, and check its permissions after the move. A password file the web server cannot read fails closed, so nobody can log in, including you. The guide to adding basic authentication to an Nginx site walks through generating the file and testing the login.
Blocking access: deny by IP and by file type
Apache blocks visitors and files with directives that changed between versions, so old .htaccess files often carry two different block styles for the same folder. Nginx keeps it to two words.
<FilesMatch "^.">
Order allow,deny
Deny from all
</FilesMatch>
Nginx, to block dotfiles such as .git and .env:
location ~ /. {
deny all;
access_log off;
log_not_found off;
}
Blocking a single IP or a range is just as direct:
location / {
deny 203.0.113.45;
deny 198.51.100.0/24;
allow all;
}
Order matters here. Nginx checks deny and allow lines in the order you write them, so put the specific blocks before the general allow all.
Headers and caching: add_header inside nginx location blocks
Caching and security headers move into nginx location blocks. Apache:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
</IfModule>
Header set X-Content-Type-Options "nosniff"
Nginx:
location ~* .(jpg|jpeg|png|webp|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
add_header X-Content-Type-Options "nosniff" always;
Two details catch people out. First, add_header in a location block replaces headers set at the server level instead of adding to them, so repeat any server-level header you still want inside that location. Second, the always flag matters: without it, Nginx skips the header on error responses such as 404s.
Common Conversion Mistakes That Break Sites
Most failed migrations come from a short list of repeat errors. The first is if inside a location block. Nginx documentation warns against it for good reason: if behaves oddly inside locations and can silently skip directives. Use a separate location block or a map instead.
The second is forgetting that Nginx location matching has its own priority order. Exact matches win, then long prefix matches, then regex in file order. A broad regex written above a specific prefix can swallow traffic meant for the specific block. The explainer on Nginx location matching works through the priority rules with examples.
The third is the missing try_files fallback: without it, a WordPress site serves its homepage fine and returns 404 for every post, because nothing routes those URLs to index.php. If posts 404 after a move, check the fallback line first.
The fourth is trailing slashes. Apache and Nginx treat /page and /page/ as different URIs, and a redirect rule written for one will not catch the other. Decide which form is canonical and redirect the other to it. The fifth is leaving the old .htaccess file on the server and assuming it still protects something. It does nothing under Nginx, so search it for every Deny and Require line and confirm each one has a Nginx twin.
Test Your Converted Rules Before Going Live
Never edit the live config and reload in the hope it works. Nginx checks syntax without touching the running server:
sudo nginx -t
sudo systemctl reload nginx
The test catches typos and missing braces, but it cannot tell you a rule sends visitors to the wrong page. For that, test with curl against a staging copy or a hosts-file entry pointing at the new server. Check the homepage, one post, one old URL that should redirect, one protected page, and one file that should be blocked. Five checks take two minutes and catch most conversion errors.
Also watch the error log while you test. A rewrite loop fills the log fast with “rewrite or internal redirection cycle” lines, and a missing try_files fallback shows up as a run of 404s for URLs that worked on Apache. The walkthrough for testing a new Nginx config without taking your site down covers the staging setup and the reload sequence in full.
When the checks pass, switch traffic and keep the Apache config and the old .htaccess file as a reference for a week. If a visitor reports a broken link, the old file tells you in seconds which rule the new config is missing.