Home › Developer Tools › Htaccess & Nginx Redirect Generator

Htaccess & Nginx Redirect Generator

Add your old and new URLs, tick the site-wide rules you need, such as forcing HTTPS or removing www, and copy ready-to-use redirect code for Apache .htaccess, Nginx or Netlify and Cloudflare Pages. Loops and mistakes are flagged as you type.

Last updated:

1. Your site
2. Redirect rules
Bulk add from a list

    
Advertisement
Advertisement

How to use the Htaccess & Nginx Redirect Generator

  1. Enter your domain and tick the site-wide rules you want, for example Force HTTPS and www → non-www.
  2. Add redirect rules: the old path on the left, the new path or full URL on the right, and the redirect type. End a path with * to redirect a whole folder.
  3. Paste a list into Bulk add if you have many URLs (one 'old new' pair per line).
  4. Press Generate redirects and pick the tab for your server: Apache .htaccess, Nginx or _redirects.
  5. Copy or download the code, put it on your server, and test a few old URLs in a private browser window.

Redirect status codes explained

CodeMeaningCached by browsersRequest methodUse it for
301Moved PermanentlyYes, often for a long timeMay change POST to GETPages and sites that moved for good (most SEO redirects)
302Found (temporary)No, unless told toMay change POST to GETTemporary moves, maintenance pages, campaigns
307Temporary RedirectNo, unless told toKept (POST stays POST)Temporary moves of forms and API endpoints
308Permanent RedirectYesKept (POST stays POST)Permanent moves of forms and API endpoints
410GoneYesNot a redirectContent removed on purpose, so search engines drop it faster than a 404

Status codes are defined in RFC 9110. For search engines, Google treats 301 and 308 as strong signals that the new URL should replace the old one in results, and 302 and 307 as weaker, temporary signals.

Reading the generated Apache rules

A rule such as RewriteRule ^blog/(.*)$ /articles/$1 [R=301,L] has three parts:

  • Pattern ^blog/(.*)$: a regular expression matched against the path without the leading slash when it is used in .htaccess. Dots and other special characters in your paths are escaped (old-page\.html), so . only matches a real dot.
  • Target /articles/$1: $1 inserts whatever the (.*) group captured, so /blog/2024/hello becomes /articles/2024/hello.
  • Flags: R=301 sends a 301 redirect, L stops processing further rules, NE stops Apache from re-encoding % in the target, G answers 410 Gone, and NC on a condition ignores letter case.

The optional /? before $ makes /old-page and /old-page/ both match. A RewriteCond line applies only to the RewriteRule directly below it.

Redirect checklist for a site migration

  1. List every old URL from your sitemap, analytics and the pages with backlinks, then map each one to its closest new page rather than sending everything to the home page.
  2. Redirect in one hop. Avoid chains such as old → interim → new; each hop adds latency and dilutes the signal. The generator flags chains between your rules.
  3. Keep the redirects for at least a year, and ideally permanently, because bookmarks and external links keep using old URLs.
  4. Update internal links and the sitemap so they point straight to the new URLs instead of relying on redirects.
  5. Test with curl -I https://example.com/old-page: you should see HTTP/2 301 and a location: header with the new URL.

Frequently asked questions

Which redirect type should I use?

Use 301 (permanent) when a page has moved for good; search engines pass its ranking to the new URL. Use 302 or 307 for temporary moves, such as maintenance or A/B tests. 308 is a permanent redirect that, like 307, keeps the request method, which matters for forms and APIs that POST. Use 410 Gone for pages removed on purpose with no replacement.

Where do I put the .htaccess code?

Put it in the .htaccess file in your website's root folder (often public_html), above any rules added by a CMS such as WordPress. The server must run Apache with mod_rewrite enabled and allow overrides (AllowOverride All). Keep a backup: a syntax error in .htaccess causes a 500 error for the whole site.

What is the difference between mod_rewrite and Redirect?

Redirect and RedirectMatch come from mod_alias and are simple and fast, but they cannot check the host name or HTTPS. RewriteRule from mod_rewrite can, which is why the site-wide presets always use it. Apache processes mod_rewrite rules before mod_alias rules, so avoid relying on the order between the two.

How do I avoid redirect loops?

A loop happens when a URL redirects to itself, directly or through other rules, for example /a to /b and /b back to /a, or a folder rule whose target is inside the same folder. The generator warns about these. Behind Cloudflare or a load balancer, use the X-Forwarded-Proto check for HTTPS, because the server itself may only see plain HTTP.

Are query strings kept?

With Keep query string on, /old?id=5 redirects to /new?id=5. Apache RewriteRule and Redirect keep query strings by default, and the Nginx code adds $is_args$args to do the same. Turn the option off to drop them in the Apache rewrite and Nginx output. Matching on a specific query string is not supported by path redirects.

Where do the Netlify and Cloudflare Pages rules go?

Save the file as _redirects (no extension) in the folder that gets published, for example public or dist. Netlify also supports domain-level rules such as www to non-www; on Cloudflare Pages use Bulk Redirects or Redirect Rules in the dashboard for those, and HTTPS is enforced automatically on both.

How do I test my redirects?

Open the old URL in a private window, or run curl -I https://example.com/old-page and check the status code and Location header. Browsers cache 301 redirects aggressively, so test with 302 first if you are unsure, and clear the cache after changing a rule.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

Robots.txt GeneratorBuild a robots.txt file with rules, sitemap lines and AI-bot blocking presets.Sitemap GeneratorTurn a list of URLs into a valid XML sitemap file.Meta Tag GeneratorCreate SEO, Open Graph and X meta tags with live previews.URL Encoder DecoderPercent-encode or decode URLs, query strings and form data.Canonical Tag GeneratorNormalize URLs and create rel=canonical tags and HTTP headers, for one page or a whole list.Chmod CalculatorConvert Linux file permissions between checkboxes, octal (755) and symbolic (rwxr-xr-x) notation.Cron Expression GeneratorBuild crontab schedules visually, read them in plain English and see the next run times.HTTP Status CodesSearch every HTTP status code with plain-English meanings, causes, fixes and RFC references.QR Code GeneratorMake QR codes for links, Wi-Fi, email and more.Barcode GeneratorCreate Code 128, EAN-13, UPC-A, EAN-8, Code 39 and ITF-14 barcodes as PNG or SVG.UUID GeneratorGenerate UUID v4 and v7 / GUIDs in bulk and copy or download them.Schema Markup Generator (JSON-LD)Create JSON-LD structured data for FAQ, Product, Article and more.Fake Data GeneratorGenerate mock data as JSON, CSV or SQL.Random String GeneratorGenerate secure random strings and tokens in bulk with any length and character set.API Key GeneratorCreate secure API keys and secrets with prefixes, checksums and SHA-256 hashes for storage.URL Slug GeneratorTurn titles into clean, SEO-friendly URL slugs: accents, stop words, separators and bulk lines.JSON Schema GeneratorTurn sample JSON into a draft 2020-12 JSON Schema with types, required fields and formats.Gitignore GeneratorBuild a .gitignore from 50+ templates for languages, frameworks, IDEs and OS, merged and deduped.License GeneratorCreate a LICENSE file for MIT, Apache, GPL, BSD, ISC, MPL or Unlicense with your name and year.ULID GeneratorGenerate sortable ULIDs and UUID v7 in bulk, monotonic option, and decode their timestamps.Htpasswd GeneratorCreate .htpasswd entries with bcrypt, APR1-MD5 or SHA-1 for Apache and Nginx basic auth.Placeholder Image GeneratorCreate placeholder images in any size, color and text as PNG, JPG, WebP, SVG or data URI.Ads.txt GeneratorCreate or validate ads.txt and app-ads.txt files: seller lines, cert IDs and variables.Docker Run to Compose ConverterConvert docker run commands to docker-compose.yml, or a compose file back to docker run.Dockerfile GeneratorGenerate a production Dockerfile and .dockerignore for Node, Python, Go or a static nginx site.HTML Boilerplate GeneratorTick the options you need and get a clean HTML5 starter template with meta, OG tags and CSS reset.JSON to Zod SchemaInfer a Zod (or Yup) schema from sample JSON with optional, nullable and z.infer types.Linux Commands Cheat SheetSearchable Linux and bash command reference with flags explained, examples and copy buttons.LLMs.txt GeneratorBuild an llms.txt file for AI crawlers: summary and link sections, import from your sitemap.Nano ID GeneratorGenerate secure Nano IDs with custom alphabet, length and count, plus a collision calculator.Nginx Config GeneratorBuild an nginx server block: static site, SPA, reverse proxy or PHP, with SSL, gzip and redirects.OpenAPI / Swagger ViewerView OpenAPI 2/3 JSON or YAML as interactive API docs with validation and an endpoint list.package.json GeneratorFill a form and get a valid, npm-ready package.json with scripts, dependencies and checks.PKCE Code Challenge GeneratorGenerate an OAuth 2.0 PKCE code_verifier and S256 code_challenge, build auth URLs, verify pairs.README GeneratorFill in a form and get a polished README.md with badges, install, usage and license, live preview.Regex GeneratorBuild regular expressions visually from blocks or presets (email, date, phone) and test them live.Commit Message GeneratorBuild Conventional Commit messages with type, scope, body, breaking change and issue refs.Database Schema DesignerDesign tables and relationships visually, then export SQL for MySQL, PostgreSQL or SQLite.Systemd Service File GeneratorCreate a systemd .service unit with ExecStart, user, restart policy, environment and hardening.tsconfig.json GeneratorBuild a tsconfig.json with target, module, strict checks and path aliases, each option explained.Access Log AnalyzerAnalyze Apache and Nginx access logs: top URLs, IPs, status codes, bots and traffic charts.Regex String GeneratorGenerate random test strings that match any regular expression, checked against the real regex.ASCII Table GeneratorTurn CSV or pasted cells into plain-text tables: MySQL, Markdown, Unicode box and reST styles.Docker Compose GeneratorBuild a docker-compose.yml with a form: services, ports, volumes, env, healthchecks and presets.Dummy File GeneratorCreate test files of an exact size in KB, MB or GB with zeros, random bytes or text.FFmpeg Command GeneratorPick a task and options, get the exact ffmpeg command with every flag explained.Folder Tree GeneratorTurn a local folder or an indented list into an ASCII directory tree for your README.GitHub Actions Workflow GeneratorBuild a GitHub Actions CI workflow: triggers, matrix, caching, tests, Pages or Docker deploy.Kubernetes YAML GeneratorGenerate Deployment, Service, Ingress, ConfigMap, Secret and HPA manifests with safe defaults.Markdown TOC GeneratorGenerate a linked table of contents from Markdown headings with GitHub-style anchors.OpenAPI EditorEdit OpenAPI/Swagger YAML or JSON side by side with live API docs, validation and download.OpenAPI ValidatorValidate OpenAPI 3.0/3.1 and Swagger 2.0 specs: schema errors, broken $refs, line numbers.Pivot Table MakerBuild pivot tables from CSV or Excel by drag and drop: sum, count, average, charts, export.SQL Query BuilderBuild SELECT queries visually: joins, filters, GROUP BY, ORDER BY and LIMIT, as clean SQL.Truth Table GeneratorType a logic expression and get its full truth table, minterms and canonical DNF/CNF.TypeScript PlaygroundWrite TypeScript with live type checking, see the compiled JavaScript and run it in your browser.Article Schema GeneratorCreate Article, BlogPosting or NewsArticle JSON-LD with headline, authors, dates and images.Event Schema GeneratorCreate Event JSON-LD with dates, venue or online location, tickets, organizer and performers.Google Search Query BuilderBuild advanced Google searches with site:, filetype:, intitle:, exact phrases and date operators.HowTo Schema GeneratorCreate HowTo JSON-LD with steps, tools, supplies, total time and cost, then copy it.Htaccess GeneratorBuild an Apache .htaccess file: HTTPS, www, gzip, caching, error pages, IP blocks, hotlinks.HTML Email Template BuilderDrag and drop blocks to build a responsive, table-based HTML email with inline styles.Organization Schema GeneratorCreate Organization JSON-LD with logo, URL, contact points, address and social profiles.PIN GeneratorGenerate random 4, 6 or 8-digit PINs that avoid sequences, repeats, dates and common PINs.Product Schema GeneratorBuild Product JSON-LD with price, availability, brand, GTIN, ratings and reviews.Question Keyword GeneratorFind the questions people ask about a topic, grouped by who, what, why, how, can and more.Recipe Schema GeneratorCreate Recipe JSON-LD with ingredients, steps, prep and cook times, nutrition and ratings.Security Headers GeneratorPick HSTS, CSP, frame, referrer and permissions options and get Apache, Nginx, Netlify or Cloudflare config.
See all 85 Code Generators & Builders →