.htaccess Apache RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https:// 301 302 HTTPS GZIP CORS

.htaccess Generator

Build Apache .htaccess rules visually — no manual syntax needed. Configure 301/302 redirects, force HTTPS, mod_rewrite URL rewrites, gzip compression, browser caching headers, CORS settings, and custom error pages using simple toggles and inputs. Presets for WordPress, Laravel, and SPA single-page apps. Conflict detection warns before rules interfere. No signup, no download.

Quick .htaccess Snippet Generator

Copy-paste ready code for the 6 most common .htaccess tasks — a 301 redirect, force HTTPS, www redirect, blocking bots, noindex, and a custom 404 page. Pick a snippet, tweak the inputs, and copy the result. Need a full file? Use the visual builder below.

301 Redirect

            
0 rules Real-time

Rule Builder

Custom 301 Redirects

Generated .htaccess

0 lines

                    
Enable rules on the left to generate your .htaccess file
Rules 0
Directives 0
Sections 0
Est. Size 0 B

What is an .htaccess File?

The .htaccess (hypertext access) file is a powerful configuration file used by Apache web servers. It lets you control URL redirects, access rules, security settings, caching behavior, and much more — all without touching the main server configuration.

Changes take effect immediately without restarting the server. The file sits in your website's root directory and applies rules to that directory and all subdirectories beneath it.

Redirects 301/302 redirects, force HTTPS, WWW handling
Security Headers, IP blocking, file protection, hotlinking
Performance Gzip compression, browser caching, Keep-Alive
Rewriting Clean URLs, trailing slashes, framework routing

Template Presets

WordPress — Pretty permalinks with index.php routing, wp-admin protection, security headers, gzip compression, and browser caching.

Laravel — Routes all requests through public/index.php, enables URL rewriting, security headers, and compression.

Static Site — Optimized for HTML/CSS/JS sites with aggressive caching, gzip compression, security headers, and custom error pages.

SPA (React/Vue/Angular) — Catches all routes and rewrites to index.html for client-side routing. Includes caching and compression.

Drupal — Clean URLs with index.php front controller, file access rules, and performance optimization.

How to Use — 3 Simple Steps

01

Configure Your Rules

Use the rule builder on the left to toggle features on and off. Expand each category to see available options. Or select a template preset to start with recommended settings for your platform.

02

Review the Output

The generated .htaccess code updates in real-time as you toggle rules. Review the syntax-highlighted output and check for any warnings about conflicting rules.

03

Copy or Download

Copy the generated code to clipboard or download it as an .htaccess file. Upload the file to your website's root directory.

Common Rules Reference

RuleDirectivePurpose
Force HTTPSRewriteCond / RewriteRuleRedirect HTTP → HTTPS for security
301 RedirectRedirect 301Permanent URL redirect (SEO-friendly)
Gzipmod_deflateCompress responses by 60-80%
Cachemod_expiresTell browsers to cache static files
Security HeadersHeader setPrevent XSS, clickjacking, MIME sniffing
Block DirectoryOptions -IndexesHide folder file listings

Common .htaccess Code Snippets (Copy & Paste)

Prefer to write the rules by hand, or just need a quick snippet? Below are the most-used .htaccess rules ready to copy and paste. Every snippet also has a matching toggle in the generator above — use whichever is faster for you. Remember to keep RewriteEngine On only once at the top of the file.

1. 301 Redirect in .htaccess

A 301 redirect is a permanent redirect that passes SEO value from the old URL to the new one. Use Redirect 301 for a single page, or RewriteRule to move an entire domain:

# Redirect a single page (old URL → new URL)
Redirect 301 /old-page.html https://example.com/new-page.html

# Redirect an entire old domain to a new domain
RewriteEngine On
RewriteRule ^(.*)$ https://newdomain.com/$1 [R=301,L]

2. RedirectMatch (Redirect with a Regex Pattern)

When you need to redirect many URLs that share a pattern, RedirectMatch uses a regular expression instead of listing every page. This example moves everything under /blog/ to /news/:

# 301 redirect an entire folder with a pattern
RedirectMatch 301 ^/blog/(.*)$ https://example.com/news/$1

3. Force HTTPS (and www / non-www)

Redirect all insecure HTTP traffic to HTTPS. This uses %{HTTP_HOST} and %{REQUEST_URI} so it works on any domain without editing:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

4. Block Ahrefs, SEMrush & Other SEO Crawlers

To block Ahrefs, SEMrush, and similar SEO spiders (which can eat crawl budget and expose your backlink data), match their user-agent and return a 403 Forbidden:

# Block Ahrefs, SEMrush, Majestic and other bots
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (AhrefsBot|SemrushBot|MJ12bot|DotBot|rogerbot) [NC]
RewriteRule .* - [F,L]

Legitimate bots respect robots.txt, but a .htaccess block enforces it at the server level for crawlers that ignore it.

5. Custom 404 Error Page

Point visitors to a friendly page when a URL is missing. The path is relative to your site root:

ErrorDocument 404 /404.html
ErrorDocument 403 /403.html
ErrorDocument 500 /500.html

6. Noindex a File or Folder with .htaccess

You can apply noindex without editing HTML by sending an X-Robots-Tag header. This example stops search engines from indexing PDFs:

# Send a noindex header for all PDF files
<IfModule mod_headers.c>
  <FilesMatch "\.(pdf)$">
    Header set X-Robots-Tag "noindex, nofollow"
  </FilesMatch>
</IfModule>

7. Password-Protect a Directory

Restrict a folder behind a username and password. Put this .htaccess inside the folder, and create a .htpasswd file (use an htpasswd generator) with your hashed credentials:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/username/.htpasswd
Require valid-user

The Default WordPress .htaccess File

If you deleted or broke your WordPress .htaccess file, this is the default WordPress .htaccess that powers pretty permalinks. Copy it into the file in your site root (the same folder as wp-config.php). WordPress manages everything between the # BEGIN WordPress and # END WordPress markers automatically:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

After restoring the file, go to Settings → Permalinks in your WordPress dashboard and click Save Changes — this forces WordPress to rewrite the rules cleanly. Select the WordPress template in the generator above to get this plus optional security headers, caching, and gzip.

How to Create an .htaccess File

The .htaccess file has no name — only the extension — which trips people up on Windows and Mac. Here's how to create one:

  1. Generate your rules above and click Download, or create a plain-text file in a code editor (VS Code, Notepad++, Sublime).
  2. Save it with the exact name .htaccess — no .txt extension. In Windows Notepad, choose "All Files" and wrap the name in quotes: ".htaccess".
  3. Upload it to your website's root directory (usually public_html or www) via FTP or your host's file manager. Enable "show hidden files" — dot-files are hidden by default.
  4. Test your site immediately. If you see a 500 Internal Server Error, a rule has a syntax problem — rename the file to disable it, then fix and re-upload.

Pro Tips

Test Before Deploying

Always test your .htaccess file on a staging server first. A syntax error can take down your entire website with a 500 Internal Server Error.

Order Matters

Apache processes .htaccess rules top to bottom. Place redirects before rewrite rules, and more specific rules before general ones.

Backup First

Always backup your existing .htaccess file before making changes. Keep a copy of the working version so you can quickly restore it.

Check mod_rewrite

Most URL rewriting requires mod_rewrite to be enabled. Check with your hosting provider if redirect rules don't work.

Frequently Asked Questions

What is an .htaccess file?

An .htaccess (hypertext access) file is a configuration file for Apache web servers. It allows you to control URL redirects, security settings, caching rules, and more on a per-directory basis without modifying the main server configuration.

Where do I place the .htaccess file?

Place the .htaccess file in the root directory of your website (public_html or www folder). The rules will apply to that directory and all subdirectories. You can also place separate .htaccess files in subdirectories for directory-specific rules.

Will these rules work on Nginx?

No. .htaccess files only work on Apache web servers. Nginx uses a different configuration syntax (nginx.conf). If you use Nginx, you will need to convert these rules to Nginx format. However, many shared hosting providers use Apache.

How do I force HTTPS on my website?

Enable the "Force HTTPS" toggle in the Redirects section. This generates RewriteCond and RewriteRule directives that detect non-HTTPS connections and redirect them to the HTTPS version. Make sure you have a valid SSL certificate installed first.

Can I use multiple rules together?

Yes! You can enable any combination of rules. The generator organizes them into proper sections with comments. The conflict detection feature will warn you if any rules might interfere with each other, like having both "add trailing slash" and "remove trailing slash" enabled.

How do I fix a "too many redirects" error caused by .htaccess?

A redirect loop usually happens when the force-HTTPS or www-redirect rule redirects the already-correct URL, creating an infinite cycle. Fix it by adding a RewriteCond to check that the request is not already on the right protocol or domain before redirecting. For example, for HTTPS: add RewriteCond %{HTTPS} off before the RewriteRule. For www redirect: add RewriteCond %{HTTP_HOST} !^www\. so it only redirects non-www requests. This generator adds the correct conditions automatically — just enable the relevant toggle.

How do I block a specific IP address using .htaccess?

To block a single IP, add: Require not ip 203.0.113.42. To block a range, use CIDR notation: Require not ip 203.0.113.0/24. For Apache 2.4+ you need these inside a <RequireAll> block alongside Require all granted. For older Apache 2.2, use: Order Allow,Deny / Allow from all / Deny from 203.0.113.42. You can also block by user-agent using SetEnvIf User-Agent "badbot" bad_bot followed by Order Allow,Deny / Allow from all / Deny from env=bad_bot.

How do I set up a 301 redirect in .htaccess?

For a single page, add: Redirect 301 /old-page.html https://example.com/new-page.html. To redirect an entire domain, use mod_rewrite: RewriteEngine On, then RewriteRule ^(.*)$ https://newdomain.com/$1 [R=301,L]. For pattern-based redirects (like moving a whole folder), use RedirectMatch 301 ^/blog/(.*)$ https://example.com/news/$1. The 301 status tells search engines the move is permanent so ranking value transfers to the new URL. You can also add custom 301 redirects with the "Custom 301 Redirects" option in the generator above.

How do I block Ahrefs, SEMrush and other crawlers with .htaccess?

Match their user-agent and return a 403. Add: RewriteEngine On, then RewriteCond %{HTTP_USER_AGENT} (AhrefsBot|SemrushBot|MJ12bot|DotBot|rogerbot) [NC], then RewriteRule .* - [F,L]. This blocks the named SEO crawlers at the server level, which saves crawl budget and keeps them from harvesting your link data. Add or remove bot names in the pattern as needed.

How do I noindex a page or file using .htaccess?

Send an X-Robots-Tag HTTP header instead of editing HTML. To noindex all PDFs, wrap a FilesMatch block that targets .pdf files inside an mod_headers IfModule, and inside it add: Header set X-Robots-Tag "noindex, nofollow". Search engines that fetch those files will see the noindex directive in the response header and drop them from the index. See the copy-paste snippet in the "Common .htaccess Code Snippets" section above. This is the standard way to noindex non-HTML files like PDFs, images, or documents.

What is the default WordPress .htaccess file?

The default WordPress .htaccess enables pretty permalinks. Inside a mod_rewrite IfModule block it sets: RewriteEngine On, RewriteBase /, a rule that leaves index.php alone, two RewriteCond lines that skip real files and folders, and a final RewriteRule that sends everything else to /index.php — all wrapped between the # BEGIN WordPress and # END WordPress markers. The full copy-paste version is in "The Default WordPress .htaccess File" section above. Place it in the same folder as wp-config.php, then go to Settings → Permalinks and click Save Changes so WordPress regenerates the rules.

How do I password-protect a folder with .htaccess?

Put an .htaccess file inside the folder with: AuthType Basic, AuthName "Restricted Area", AuthUserFile /full/path/to/.htpasswd, Require valid-user. Then create a .htpasswd file containing a username and a hashed password (generate the hash with an htpasswd tool). Use the absolute server path to .htpasswd, and store it outside your public web root when possible for extra security.