How to set up a 301 redirect in .htaccess and nginx
Server-level 301 redirects are the fastest, most reliable way to redirect URLs — no plugin overhead. Here are copy-paste examples for both Apache (.htaccess) and nginx, from single URLs to whole-domain rules. Always back up the file first; a syntax error can take the site down.
Apache (.htaccess): redirect a single URL
Using mod_alias, this is the simplest form. Place it in the .htaccess file at your site root:
Redirect 301 /old-page https://example.com/new-pageApache: redirect a pattern with mod_rewrite
To move an entire directory (or match a pattern) and preserve the rest of the path:
RewriteEngine On
RewriteRule ^old-directory/(.*)$ /new-directory/$1 [R=301,L]Apache: force www → non-www and HTTP → HTTPS
A common canonicalization rule that consolidates all traffic onto the secure apex domain:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]Nginx: redirect a single URL
Add this inside the relevant server block, then reload nginx:
location = /old-page {
return 301 https://example.com/new-page;
}Nginx: redirect a pattern
Use rewrite ... permanent to move a directory while keeping the sub-path:
rewrite ^/old-directory/(.*)$ /new-directory/$1 permanent;Nginx: force www → non-www and HTTP → HTTPS
A dedicated server block that 301s all www/insecure traffic to the canonical host:
server {
listen 80;
listen 443 ssl;
server_name www.example.com;
return 301 https://example.com$request_uri;
}Test your redirect
After deploying (and reloading nginx with 'sudo nginx -s reload'), confirm the status code and destination from the command line:
curl -I https://example.com/old-page
# Look for: HTTP/1.1 301 Moved Permanently
# and a Location: header pointing to the new URLAutomate 404 recovery with Redirect Mapper
Hand-writing server rules is perfect for a known set of redirects — but you still have to discover every broken URL first. Redirect Mapper logs each 404 in real time and lets you export a clean list of source and destination URLs, so building your .htaccess or nginx rules becomes copy-paste.
Frequently asked questions
Add the redirect rule to the .htaccess file in your site's root directory. Rules using mod_rewrite should come after 'RewriteEngine On'. Always back up the file first, since a syntax error can return a 500 error for the whole site.