.htaccess, Nginx & Caddy Rule Generator
Pick a preset or flip the switches — force HTTPS, fix www and trailing slashes, bulk redirects, security headers, AI crawler blocking, caching — and copy correctly-ordered code for Apache, LiteSpeed, Nginx, Caddy or Cloudflare. No regex required.
Writing rewrite rules by hand is where most small mistakes happen — a missing flag, the wrong rule order, a redirect chain that adds an extra hop, or a regex that works for Apache but does nothing on Nginx (which never reads a .htaccess file at all). This generator builds correct, ready-to-paste code for four servers plus Cloudflare, updates live as you toggle options, and gives you a link to the exact configuration so you can save it or share it.
Start from a preset, then fine-tune. The code below updates instantly.
Redirects
Redirect every plain HTTP request to HTTPS with a permanent (301) redirect.
Pick www or non-www so only one is indexed. Combined with HTTPS into a single redirect — no chains.
Enforce one URL format. Leave off for WordPress — it already follows your permalink setting.
Turn /about.php into /about. Old links redirect to the clean address, and the clean address still opens your file. For hand-built PHP and static sites; WordPress and most frameworks already have clean URLs.
Paste old and new URLs, one pair per line. Chains are shortened automatically, so every old URL goes straight to its final address in one hop.
Moving to a new domain? Every page on the old domain goes to the same page on your domain, in one hop. Pages you renamed in Bulk redirects go straight to their new address.
Your new domain is the one in “Your domain” below.
Show your own page instead of the server’s plain default for 404, 403 and 500 errors. Leave a box empty to skip it.
Paths to pages on your own site. WordPress themes already show their own 404 page, so leave that box empty on WordPress.
Security & bots
X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy, plus HSTS when Force HTTPS is on.
Forces HTTPS on every subdomain, so only tick it if they all have a certificate. Preloading is hard to undo — submit at hstspreload.org when ready.
Report-only mode logs violations in the browser console without blocking anything, so it can’t break your site.
GPTBot, ClaudeBot, CCBot, Bytespider, Meta and more — plus a matching robots.txt. Pick whole groups or individual bots.
Blocking search fetchers also removes your pages from AI answers and their citations.
Return a 403 to SEO crawlers, vulnerability scanners and scripted traffic. Each group is a separate choice.
Scripting tools are also used by uptime monitors, webhooks and integrations. Check that none of yours rely on them first.
Deny .env, .git, other dotfiles, backups, SQL dumps and logs. Keeps .well-known open for SSL.
Stop the server showing a file list for folders without an index page.
Lock down the files and URLs attackers probe first on WordPress sites.
Ask for a username and password before anyone can open a folder, such as a staging copy or admin area, or the whole site.
Use / to protect the whole site. The password file is where Apache and Nginx look for your login; keep it outside your public web folder.
Return a 403 to specific IP addresses or ranges, such as a scraper or attacker you’ve spotted in your logs.
Stop other websites from embedding your images and using your bandwidth. Your own pages, search engines and direct visits still load them. Uses your domain below.
Performance
Gzip text, CSS, JS, JSON, SVG and fonts (zstd + gzip on Caddy). LiteSpeed does this automatically.
Cache images, CSS, JS and fonts for a year; never cache HTML. Assumes versioned asset URLs (WordPress adds ?ver=).
Serve photo.jpg.webp automatically when it exists next to photo.jpg and the browser supports WebP.
server_name, Caddy’s site address, Cloudflare rules, redirect targets and hotlink protection. Apache’s other rules work for any domain automatically.Open source on GitHub (MIT licence) · Output executed against Apache 2.4, Nginx 1.24 and Caddy 2.9, October 2026; LiteSpeed and Cloudflare output follows each vendor’s documented syntax
If you’re writing about .htaccess, Nginx or Caddy config, or WordPress security, here’s a ready-to-paste link to this generator.
How to use the generated code
Each server reads its rules from a different place, and putting them in the wrong place is the most common mistake with a tool like this.
On a WordPress site, your .htaccess file already has a # BEGIN WordPress / # END WordPress block that handles permalinks. Paste the generated code above that block, not inside or below it — WordPress will overwrite anything inside its own block the next time you resave permalinks, and rules placed after it may never run. LiteSpeed reads the same file, so the Apache output works there unchanged.
Nginx has no .htaccess support on any host, so the Nginx output goes into your server config: the map blocks once inside http {}, the rest in your site’s server {} blocks (commonly /etc/nginx/sites-available/yoursite.conf), with the deny rules placed above your PHP location. Then run nginx -t and reload.
Caddy obtains certificates and redirects HTTP to HTTPS automatically, so its output is shorter. Merge the generated directives into the matching site block of your Caddyfile, keep your existing root, php_fastcgi and file_server lines, then run caddy validate and caddy reload.
The Cloudflare tab turns the same switches into WAF custom rules that stop bots, AI crawlers, file probes and blocked IP addresses at Cloudflare, before they reach your server. Use it alongside your server’s tab, not instead of it: headers, caching and redirects still come from your server rules. Each block in the tab is one custom rule — paste its expression, set the action to Block and deploy.
A malformed rewrite rule can create a redirect loop or lock visitors out entirely — and because .htaccess takes effect immediately with no restart required, a mistake shows up in production right away. Download a copy of your existing config before editing it, so you can restore it in seconds if something goes wrong.
Vulnerability scanners are the easy one. Real visitors never use them, so blocking them costs you nothing.
Scripting tools like python-requests need a quick check first. Attack scripts use them, but so do many uptime monitors, webhooks and integrations, so make sure none of yours do before you block them.
SEO crawlers like AhrefsBot and SemrushBot are a business decision, not a security one. They’re run by legitimate companies, and blocking them only stops those tools from crawling and auditing your pages.
Either way, this only stops tools that announce themselves. Anyone who disguises their bot as a normal browser gets through, so treat it as a filter, not a firewall.
What each rule actually does
Checks whether the request arrived over plain HTTP or on the wrong host, and sends it to the one correct HTTPS address with a single 301 (permanent) redirect. Doing both in one rule matters: separate rules turn http://www.example.com into two redirect hops, which slows the first visit and dilutes link signals. If your site sits behind Cloudflare or another proxy, the Apache output includes a commented alternate line, because the standard check can misread the connection as insecure even when it reached your visitor over HTTPS.
Makes /page and /page/ resolve to one URL instead of two copies of the same content. Real directories and files with extensions are left alone, and only normal page requests are redirected. Leave it off on WordPress, which already redirects to match your permalink structure — adding a second rule can fight it.
Gives a hand-built site clean addresses like /about instead of /about.php. Two things happen: anyone who opens the old address is redirected to the clean one, and the clean address quietly serves your existing file, so you don’t rename anything. Only normal page visits are redirected, so forms that send data to a .php file keep working, and WordPress’s own files are left alone. After switching it on, update the links in your menus to the clean addresses.
For site migrations and URL clean-ups. Each old path matches with or without a trailing slash and goes straight to its final HTTPS address. If your list contains chains — one line sends /a to /b and another sends /b to /c — the generator sends /a straight to /c, and it removes and flags lines that loop back on each other. Choose 301 for permanent moves and 302 for temporary ones. Query strings on old URLs are ignored when matching. Any query string the visitor arrives with is kept, and added to the new URL’s own query string if it has one.
The core headers stop MIME sniffing, block your pages being framed by other sites, limit referrer leakage and switch off browser features you don’t use. HSTS tells browsers to use HTTPS only, so it’s added only when Force HTTPS is on, and it covers just your main domain. The preload option extends it to every subdomain and qualifies you for the browser preload list, which is effectively permanent, so only enable it when every subdomain has a certificate. The Content-Security-Policy starter runs in report-only mode, so you can watch the browser console for violations before enforcing anything.
Returns a 403 to AI crawlers that identify themselves in their User-Agent, and adds a robots.txt tab for the ones that only respect robots.txt. Two of them, Google-Extended and Applebot-Extended, aren’t separate crawlers at all — they’re robots.txt tokens that tell Google and Apple not to use your content for AI training — so they appear only in the robots.txt output. Open Choose individual bots to untick any bot you want to allow; each one is labelled with its company and what it does.
Automated scanners request /.env, /.git/config and backup.sql on millions of sites every day, because one exposed file can leak database passwords. These rules deny every dotfile except .well-known (which SSL certificate validation needs), plus backups, logs, SQL dumps and package manifests. Disabling directory listing stops folders without an index page from showing their contents.
For a domain change, such as a rebrand. Every address on the old domain, with or without www, goes to the same address on your new domain with a single 301 redirect, which is how search engines know to pass the old domain’s rankings to the new one. If you also renamed pages, list them in Bulk redirects and the old domain sends them straight to their final address. Both domains need to point at your server, or you can put these rules on the old server instead. Keep the old domain registered and redirecting for at least a year.
Shows a login box before anyone can open the folder you choose, or the whole site. It’s the simplest way to keep a staging copy or test area away from visitors and search engines. Your password is turned into a scrambled code (a hash) in your browser, so the real password is never stored or sent anywhere, and it isn’t included in share links. Apache and Nginx read the login from a small password file you create; Caddy keeps it in the Caddyfile. The /.well-known/ folder stays open so your SSL certificate can still renew.
Hotlinking is when another site shows your images by pointing at your files, so your server pays for their traffic. This rule refuses image requests that come from other websites, while your own pages, search engines, social previews and people opening an image directly still get it. It checks the Referer header, so it needs your domain filled in.
Returns a 403 to the addresses or ranges you list, IPv4 or IPv6. If your site sits behind Cloudflare or another proxy, your server sees the proxy’s address instead of the visitor’s, so put IP blocks in the Cloudflare tab instead.
Blocks xmlrpc.php, the most common target for password-guessing attacks; denies direct requests for wp-config.php; stops PHP from running inside the uploads folder, where a malicious upload would try to execute; and blocks ?author=1 scans that reveal usernames. Only block xmlrpc.php if you don’t use Jetpack or an app that publishes through it.
Compression typically shrinks HTML, CSS and JavaScript by 60–80% on the way to the browser. Browser caching tells returning visitors to reuse images, CSS, JavaScript and fonts for a year instead of downloading them again, while HTML is never cached so content updates appear immediately.
This rule does not create WebP images for you — it only serves one if it already exists next to the original (a plugin like ShortPixel, Imagify, or a build step typically creates the .webp file). Once that file exists, this rule detects that the visitor’s browser supports WebP and serves the smaller file automatically, without changing any image URLs in your content.
Replaces the server’s plain error screens with pages you’ve made, such as a friendly 404 with a search box. Point each code at a page that exists on your site. On Caddy, the 403 page shows for errors the server raises itself, not for the requests these rules block.
Bot blocking, AI crawler blocking, sensitive-file protection, WordPress hardening and IP blocking become WAF custom rules, so unwanted requests are stopped before they reach your server. Bulk redirects become a list you can import into Cloudflare’s Bulk Redirects, and switches that are simple Cloudflare settings, like Always Use HTTPS, are listed with where to find them.
Frequently Asked Questions
The most common cause is pasting new rules inside or below WordPress’s own # BEGIN WordPress block, or a typo in a RewriteCond/RewriteRule pair that creates a redirect loop. Always add custom rules above that block, and keep a backup of the working file so you can restore it immediately if the site stops loading. If you see a 500 error right after adding the rules, your host may not allow the Options line — delete it and reload.
No. Nginx was designed without per-directory config file support for performance reasons — every directive has to live in the main server configuration. If your host runs Nginx, use the Nginx output above and apply it through your host’s config editor or SSH access, not by uploading a .htaccess file.
Check your hosting control panel — cPanel almost always means Apache or LiteSpeed (both read .htaccess), while a custom VPS or cloud panel more often means Nginx. You can also check response headers: open your browser’s network tab and look for a Server header reading Apache, nginx, LiteSpeed or Caddy. When genuinely unsure, try the Apache output first — if .htaccess changes have no effect at all, you’re very likely on Nginx.
Yes. LiteSpeed Web Server reads .htaccess natively and understands the same rewrite, header and access rules, so use the Apache tab unchanged. OpenLiteSpeed is more limited: it reads only the rewrite rules from .htaccess (other directives are ignored) and must be restarted after changes, so set headers and access rules in its WebAdmin console instead.
Yes — this rule redirects every visitor to the HTTPS version of your site, so if no valid SSL certificate is installed, visitors will hit a browser security warning instead of your content. Confirm your SSL certificate is active first (most hosts now issue a free one automatically via Let’s Encrypt) before enabling this rule.
Blocking AI training crawlers has no effect on Google or Bing rankings, so it’s a low-risk choice if you don’t want your content used to train models. Blocking AI search and assistant fetchers is a bigger decision: it keeps your pages out of answers in ChatGPT search, Perplexity and similar tools, including the links they show back to sources. Many sites block training crawlers and allow search fetchers.
Because they aren’t crawlers. Google and Apple crawl with their normal search bots and check robots.txt for these two tokens to decide whether your content can be used for AI training. Blocking them at the server would mean blocking Googlebot or Applebot, which would remove you from search. They belong in robots.txt, which is why the generator adds them there.
Turn on Bulk redirects and paste your list — one old and new URL per line, separated by a space, tab or comma (a two-column spreadsheet pastes in directly). For Nginx the generator uses a single map, which stays fast even with thousands of entries. On Apache, hundreds of rules are fine; for many thousands, a server-level RewriteMap or a redirect plugin is more efficient.
It breaks anything that still uses XML-RPC: Jetpack, some remote-publishing and backup services, and older mobile apps. Modern WordPress features use the REST API instead, so most sites lose nothing. If you rely on Jetpack, leave that one checkbox off and keep the other hardening rules.
Yes. Click Copy share link above the code. The link reopens this generator with every switch, your domain, your redirects, your IP list, your bot choices and the selected tab exactly as you left them (never your username or password) — useful for saving a setup, sending it to a developer, or pointing to it in a forum answer.
No. Apache reads .htaccess on every request, so changes apply the moment you save the file. LiteSpeed checks for changes every few seconds, so give it about ten seconds before you test. Either way there’s no restart step to catch a mistake first, so an error shows up on your live site straight away.
Yes. After saving changes to your Nginx config, run nginx -t to check the syntax, then reload with systemctl reload nginx (or your host’s equivalent). A reload is the safe option here — if the new config is invalid, Nginx keeps the old one running and your site stays up. A full restart is riskier, since a bad config there can leave no process running at all. Either way, always run nginx -t first.
No. These are third-party SEO tools, not search engines, so blocking them has no effect on how Google or Bing crawl or rank your site. The trade-off is that those tools can no longer crawl your pages, so their site audits and content reports stop working for your site, for you and for competitors. Your backlink data is not affected: these tools find links to you by crawling the sites that link to you, not your own site.
This rule is a traffic director, not an image converter — it checks whether a .webp file already sits next to the original and serves it only if so. Creating the actual .webp files is a separate step, usually handled by an image optimization plugin (ShortPixel, Imagify, EWWW) or a build process. Without that file existing, the rule silently falls through and serves your original image, so nothing breaks either way.
Yes. Use your server’s tab as normal, then add the Cloudflare tab’s rules in your Cloudflare dashboard to stop bots, AI crawlers and file probes before they reach your server. Put IP blocks in Cloudflare too: behind Cloudflare, your server sees Cloudflare’s addresses instead of the visitor’s, so server-level IP rules won’t match.
The generator fixes chains for you. If one line sends /a to /b and another sends /b to /c, the output sends /a straight to /c, so visitors and search engines never pass through an extra redirect. Lines that loop back on each other, like /a to /b and /b to /a, are removed and flagged, because they would redirect forever.
Use 301 for pages that have moved for good, such as a site migration or renamed URLs: search engines pass the old page’s ranking to the new one, and browsers remember the redirect. Use 302 only for short-term moves, like a seasonal page, when you plan to bring the old URL back.
Turn on Move from an old domain, type the old domain, and put your new domain in Your domain. Every page on the old domain then goes to the same page on the new one with a single 301 redirect, with or without www, and keeps any tracking codes in the address. If you renamed some pages during the move, add them to Bulk redirects and they will go straight to their new address. Keep the old domain registered and redirecting for at least a year.
Turn on Password-protect a folder, enter the folder (or / for the whole site), a username and a password. The generator gives you the rules plus one line to save in a password file. On Apache and Nginx, create that file outside your public folder and check that the path in the rules matches it. Your password is hashed in your browser and never sent anywhere.
Correct server rules shouldn’t
require memorizing regex.
A single missing flag or misplaced rule in a server config can silently do nothing, or actively break your site — and the most common web servers don’t even share a syntax, let alone a config file. This generator exists so you can get the exact, correctly-ordered code for your actual server, without needing to become a regex expert to do it safely.
Pick a preset, copy it once, and paste it in the right place.