.htaccess RewriteRule Generator
Updated October 2026Build Apache mod_rewrite rules without memorising the syntax: pick a recipe or write your own pattern, add RewriteCond conditions and flags, test it on a real URL and copy the finished .htaccess block. Free, runs in your browser.
Advertisement
Advertisement
1. Start from a recipe
Redirect /old-blog/anything to /blog/anything with one rule.
2. Conditions (RewriteCond)
No conditions: the rule applies to every request whose path matches the pattern.
3. The rule (RewriteRule)
Your .htaccess code
RewriteEngine On
RewriteRule ^old-blog/(.*)$ /blog/$1 [R=301,L]What it does, line by line
- Rule: when the path (without its leading slash) matches ^old-blog/(.*)$, send a permanent (301) redirect to /blog/$1, where $1, $2... are the parts captured by the parentheses in the pattern. Flags: no later rule is applied (L).
Test the rule on a URL
Simulates how Apache would treat this request in a root .htaccess file.
Matches. The visitor is redirected to https://www.example.com/blog/my-post?utm_source=newsletter
What a RewriteRule Is and When You Need One
RewriteRule is the main directive of Apache's mod_rewrite. It compares the requested URL path against a regular expression and, when it matches, either serves a different file (an internal rewrite, invisible to the visitor) or sends the browser to a different URL (a redirect, visible in the address bar). One rule can handle an unlimited number of URLs because the pattern captures parts of the path and the substitution reuses them.
You need a RewriteRule rather than a plain Redirect or RedirectMatch when the decision depends on more than the path: the protocol (force HTTPS), the host name (www or non-www), the query string (turn ?id=42 into /42), or whether a file exists (clean URLs that fall through to a script). Those extra checks are written as RewriteCond lines directly above the rule, and that is exactly what this generator builds: the conditions, the rule, the flags, and a plain-English explanation so you can review it before it goes into your .htaccess.
If you only need to send one URL to another, the simpler .htaccess redirect generator writes exactRedirectMatch rules, and the bulk redirect generator handles a whole list.
RewriteRule Syntax Explained
RewriteEngine On
RewriteCond TestString CondPattern [flags] # optional, zero or more
RewriteRule Pattern Substitution [flags]| Part | What it is | Example |
|---|---|---|
| Pattern | A Perl-compatible regular expression matched against the URL path. In a .htaccess file the path has no leading slash, so write ^blog/ not ^/blog/. | ^old-blog/(.*)$ |
| Substitution | Where the request goes. A path starting with / stays on the same host; a full https:// URL is an external redirect; a bare file name is relative to the .htaccess directory; - (a dash) means "leave the URL alone, just apply flags". | /blog/$1 |
| $1 … $9 | Back-references to the groups in parentheses in the Pattern. | $1 = whatever (.*) matched |
| %1 … %9 | Back-references to the groups in the last matching RewriteCond. | %1 = the id captured from the query string |
| %{VARIABLE} | Server variables: HTTP_HOST, HTTPS, REQUEST_URI, QUERY_STRING, REQUEST_FILENAME and others. | https://%{HTTP_HOST}/$1 |
| [flags] | Comma-separated options in square brackets that change how the rule behaves. | [R=301,L] |
RewriteRule Flags: R, L, NC, QSA, QSD, NE and Others
| Flag | Meaning | When to use it |
|---|---|---|
| R=301 | Redirect with a permanent status code. | Any URL move you want search engines to pass rankings through. Without a code, R alone sends 302. |
| R=302 | Temporary redirect. | Maintenance pages, A/B tests, anything that will be undone. |
| L | Last: stop processing rules after this one. | Almost always with a redirect. Without L the rewritten URL keeps running through later rules in the file. |
| NC | No case: the Pattern matches regardless of upper or lower case. | When old links exist in mixed case, e.g. /About and /about. |
| QSA | Query string append: keep the request's original query string and add it to the one in the substitution. | Internal rewrites to a script that also needs the visitor's own parameters (?page=2). |
| QSD | Query string discard: drop the original query string. | Redirects where tracking parameters should not follow the user to the new URL. |
| NE | No escape: do not percent-encode special characters in the substitution. | Targets that contain # anchors or already-encoded characters. |
| END | Like L, but also stops the per-directory rewrite loop entirely (Apache 2.4+). | Complex .htaccess files where a rewritten URL would otherwise be re-matched. |
| F | Forbidden: answer 403. | Blocking hotlinking or bad bots. |
| G | Gone: answer 410. | Content that was removed on purpose and should drop out of the index. |
| PT | Pass through to the next handler. | Mostly needed in server config, not .htaccess. |
A detail that trips people up: in a .htaccess file, after a rule with L matches, Apache restarts the rewrite process with the new URL (the per-directory loop). That is why an internal rewrite to product.php needs a RewriteCond %{REQUEST_FILENAME} !-f guard: on the second pass the new URL points at a real file, the condition fails, and the loop ends.
Common .htaccess RewriteRule Recipes
These are the recipes the generator offers, with the output it produces.
Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]Behind a load balancer or Cloudflare, %{HTTPS} is often "off" even for secure requests. Use the forwarded header instead: RewriteCond %{HTTP:X-Forwarded-Proto} !https.
Redirect non-www to www (or the reverse)
# non-www -> www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# www -> non-www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]Combine the host and HTTPS checks into one rule where you can, so visitors get a single 301 instead of a chain (http → https → www).
Move a folder and keep the rest of the path
RewriteRule ^old-blog/(.*)$ /blog/$1 [R=301,L]Add or remove a trailing slash
# add (skip real files)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [R=301,L]
# remove (skip real directories)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]Remove .html from URLs
# 1. redirect the old .html address to the clean one
RewriteCond %{THE_REQUEST} \s/([^\s?]+)\.html[\s?] [NC]
RewriteRule ^ /%1 [R=301,L]
# 2. serve the file internally when the clean URL is requested
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L]The generator writes the first rule from its recipe; the second is needed so the clean URL still finds the file. The THE_REQUEST condition is what prevents a loop between the two.
Query string to clean URL
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule ^product\.php$ /product/%1? [R=301,L]The pattern cannot see the query string, so the id is captured in a RewriteCond and reused as %1. The trailing ? in the substitution drops the old query string; QSD does the same thing.
Clean URL to script (internal rewrite)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [L,QSA]RewriteCond: Adding Conditions to a Rule
Each RewriteCond applies to the first RewriteRule below it, and by default all conditions must be true (add [OR] to a condition to change that). The test string is usually a server variable; the pattern is a regex, a comparison, or a file test:
| CondPattern | Meaning |
|---|---|
| !^www\. [NC] | Does not start with "www.", case-insensitive |
| -f / !-f | Is / is not an existing regular file |
| -d / !-d | Is / is not an existing directory |
| -s | Is an existing file with a size greater than zero |
| =value | Exact string comparison (lexical) |
| >value / <value | Lexically greater or smaller than |
| off / on | Typical values of %{HTTPS} |
The most useful variables in .htaccess are HTTP_HOST (the domain the visitor typed), HTTPS, REQUEST_URI (the full path with its leading slash), QUERY_STRING, REQUEST_FILENAME (the path on disk), THE_REQUEST (the raw request line) and HTTP_USER_AGENT.
Mistakes That Cause 500 Errors and Redirect Loops
- A leading slash in the pattern.
^/blognever matches in .htaccess; the generator warns about this. - A catch-all redirect without a condition.
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]also matches the destination and loops forever. Add a RewriteCond on the host or protocol. - Internal rewrites that match their own output. Guard them with
!-f/!-dor make the pattern specific. - Forgetting RewriteEngine On. Without it every RewriteRule is ignored (no error, just nothing happens).
- Unescaped dots. In a regex
.matches any character; write\.htmland\.php. - Putting the rule after the CMS block. WordPress ends its block with a catch-all to index.php and the L flag, so your rule never runs. Put redirects above
# BEGIN WordPress. - mod_rewrite not enabled or
AllowOverride Noneon the host: the file is ignored or returns 500. Check with your host before debugging the regex. - Browser cache. 301 responses are cached aggressively; test changes in a private window or with the broken link checker, which shows the first response without caching.
How to Test a RewriteRule
- Paste a real URL into the tester above. It applies the conditions and the pattern the way a root .htaccess would and shows the final URL, or tells you which part did not match. To test a whole file with several rules, use the .htaccess tester.
- Deploy to a staging copy first if you can. Keep a backup of the previous .htaccess; a syntax error returns 500 for the whole site.
- Request a few old URLs with the broken link checker: each should answer 301 with the expected Location, and the target should answer 200.
- Check that real files (images, CSS) and the admin area still load;
!-fconditions exist for that reason. - Watch Search Console's Pages report for a week after a large change for "Redirect error" or "Page with redirect" spikes.
Other Redirect Generators
For plain URL-to-URL redirects on any server, or a long list of them, use the dedicated generators:
How to Use
- 1
Pick a recipe (force HTTPS, www redirect, trailing slash, clean URLs, folder move) or start from a custom rule
- 2
Adjust the conditions (RewriteCond), the regex pattern and the substitution; the .htaccess code updates as you type
- 3
Choose 301, 302 or an internal rewrite and tick the flags you need (L, NC, QSA, QSD, NE)
- 4
Paste a real URL into the tester to see whether the rule matches and where the request ends up
- 5
Read the line-by-line explanation and the warnings, then copy the block or download it as .htaccess
Why This Tool Matters for SEO
A wrong RewriteRule takes a whole site offline with a 500 error or traps visitors and Googlebot in a redirect loop, while a correct one lets you move sections, enforce HTTPS and a single host name, and serve clean URLs with a single line. Writing the regex, the conditions and the flags by hand is where the mistakes happen; generating the rule from a tested recipe and simulating it on a URL before you deploy removes most of them.
Frequently Asked Questions
What is the difference between RewriteRule and Redirect in .htaccess?
Redirect and RedirectMatch (mod_alias) only compare the URL path and send the browser elsewhere. RewriteRule (mod_rewrite) can use regular expressions with captured groups, can check conditions such as the protocol, host name, query string or whether a file exists, and can rewrite internally without changing the visible URL. Use Redirect for simple one-to-one moves and RewriteRule when a pattern or a condition is involved.
Why does my pattern starting with ^/ never match?
Inside a .htaccess file Apache strips the directory prefix before matching, so the path it compares has no leading slash. Write ^blog/ instead of ^/blog/. In the main server configuration (httpd.conf or a VirtualHost) the leading slash is present, which is why examples copied from there fail in .htaccess.
What do the flags R=301, L, NC and QSA mean?
R=301 sends a permanent redirect (R alone sends 302). L marks the rule as the last one to run for this request. NC makes the pattern case-insensitive. QSA keeps the original query string and appends it to the substitution, which internal rewrites to a script usually need. QSD discards the query string and NE stops Apache from percent-encoding the target.
How do I force HTTPS with .htaccess?
Add RewriteCond %{HTTPS} off followed by RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] at the top of the file, above any CMS rules. If the site sits behind a proxy or CDN that terminates TLS, test %{HTTP:X-Forwarded-Proto} !https instead, because %{HTTPS} may always be off there.
How do I redirect www to non-www (or non-www to www)?
For non-www to www: RewriteCond %{HTTP_HOST} !^www\. [NC] then RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]. For www to non-www: RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] then RewriteRule ^(.*)$ https://%1/$1 [R=301,L]. Both recipes are built into the generator.
Why do I get a redirect loop or a 500 error after adding a rule?
A loop means the rule also matches the URL it redirects to; a catch-all pattern without a RewriteCond is the usual cause, and the tester on this page flags it. A 500 error means Apache could not parse the file (a typo, an unclosed bracket, a flag it does not know) or mod_rewrite is not enabled. Restore the previous .htaccess, then add the rule back and check the server error log.
Does the tester run my real server configuration?
No. It simulates a single rule in a root .htaccess: it evaluates the conditions it understands (HTTPS, HTTP_HOST, QUERY_STRING), assumes the path is not an existing file or directory, applies the regex and builds the resulting URL. Other rules in your file, server-level configuration and modules such as mod_alias are not part of the simulation, so always verify on the live server with a few requests.
Related Tools You Might Like
Meta Tags Generator
Generate optimized meta tags for your pages
Google SERP Preview
Preview how your page appears in Google search results. Optimize titles and descriptions for CTR
Robots.txt Generator
Create and validate robots.txt files for search engine crawlers
JSON-LD Schema Generator
Generate structured data (JSON-LD) for rich snippets
Related Guides
More in Technical SEO tools · All free SEO tools