.htaccess & Nginx Server Rules Generator

Generate battle-tested Apache and Nginx server configurations. Enforce 301 HTTPS encryption, canonical www/non-www domains, shield sensitive .env files, prevent directory traversal, and map batch redirect rules.

Server Directive Builder

Canonicalization & Security Toggles

Batch 301 Permanent Redirects

→
→
.htaccess Output
# ==================================================================
# Apache .htaccess Production Hardening & SEO Rules
# Generated for: example.com
# WeSecureX Technical Security & SEO Suite
# ==================================================================

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # 1. Enforce HTTPS 301 Redirect
  RewriteCond %{HTTPS} off [OR]
  RewriteCond %{HTTP:X-Forwarded-Proto} =http
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  # 2. Canonicalization: Redirect WWW to Non-WWW
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

  # 3. Custom 301 Permanent Redirects
  RewriteRule ^old-about-us$ /about [R=301,L]
  RewriteRule ^services/audit$ /scanner [R=301,L]
</IfModule>

# ==================================================================
# Directory Browsing Protection
# ==================================================================
Options -Indexes

# ==================================================================
# Block Access to Hidden & Sensitive Files (.env, .git, .yml, .bak)
# ==================================================================
<FilesMatch "^\.(.*)|.*\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist|env|yml|yaml)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order deny,allow
    Deny from all
  </IfModule>
</FilesMatch>

# ==================================================================
# HTTP Security Response Headers
# ==================================================================
<IfModule mod_headers.c>
  # Strict-Transport-Security (HSTS 2-Year Max-Age + Preload)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
  # Prevent MIME-type sniffing
  Header always set X-Content-Type-Options "nosniff"
  # Clickjacking defense
  Header always set X-Frame-Options "SAMEORIGIN"
  # Referrer policy
  Header always set Referrer-Policy "strict-origin-when-cross-origin"
  # Permissions policy
  Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
</IfModule>

# ==================================================================
# Block Known Vulnerability & Scraper User-Agents
# ==================================================================
<IfModule mod_rewrite.c>
  RewriteCond %{HTTP_USER_AGENT} (nikto|sqlmap|acunetix|havij|nmap) [NC]
  RewriteRule .* - [F,L]
</IfModule>

Web Server Architecture: Apache mod_rewrite vs. Nginx

Server-level configuration files sit at the perimeter of your web infrastructure. Before a single line of PHP, Node.js, or Python code executes, the web server evaluates routing and access control directives.

In Apache HTTP Server, .htaccess files provide decentralized, directory-level configuration. In Nginx, rules must be centralized within the master server configuration block because Nginx uses an asynchronous, event-driven architecture that avoids repetitive file-system lookups. Regardless of the engine you operate, enforcing strict HTTPS transport and blocking directory browsing are fundamental security requirements.

Directives Comparison: Apache .htaccess vs. Nginx Configuration

Security / SEO FeatureApache .htaccess SyntaxNginx SyntaxVulnerability / Penalty Mitigated
Force HTTPS 301RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://...
return 301 https://$host$request_uri;Prevents unencrypted cleartext interception
Block Dotfiles (.env, .git)<FilesMatch "^\.">
Require all denied
</FilesMatch>
location ~ /\. {
deny all;
}
Blocks API key and database credential leaks
Disable Directory ListingOptions -Indexesautoindex off;Prevents attackers from browsing folder contents
Clickjacking ShieldHeader always set X-Frame-Options SAMEORIGINadd_header X-Frame-Options "SAMEORIGIN";Stops malicious iframe overlay attacks
HSTS PreloadHeader set Strict-Transport-Security "max-age=..."add_header Strict-Transport-Security "...";Immunizes against SSL-stripping attacks

Understanding Apache Rewrite Flags

Directives like RewriteRule ^(.*)$ https://example.com/$1 [R=301,L,NE] utilize flags enclosed in brackets. [R=301] instructs Apache to issue a permanent redirect. [L] stops evaluating rules in the current iteration. [NC] enforces case-insensitivity. Always place specific redirect rules above generic catch-all rules.

Eliminating Intermediate Redirect Chains

Redirect chains occur when a request goes from http://example.com -> http://www.example.com -> https://www.example.com -> https://example.com. Each hop adds 150-300ms of latency and dilutes link equity. Our generator unifies HTTPS and domain normalization into a single 1-hop 301 redirect.

Server Configuration Deployment Checklist

✓Always retain a timestamped backup of existing server configuration files
✓Enforce 301 HTTPS redirection with 1-hop canonical domain normalization
✓Explicitly block access to .env, .git, and backup archive files
✓Disable directory listing with `Options -Indexes` or `autoindex off;`
✓Configure HSTS with at least 1-year max-age (31536000 seconds)
✓Validate response headers using the WeSecureX Security Headers Checker

Frequently Asked Questions

Expert answers regarding Apache rewrite rules, Nginx configurations, and server hardening.

Where should the generated .htaccess file be uploaded?

Upload the .htaccess file directly to your website's document root directory (commonly named `public_html/`, `www/`, `htdocs/`, or `web/`). Ensure your FTP client or hosting control panel has 'Show hidden files (dotfiles)' enabled, as files prefixed with a dot are hidden by default in Unix-like operating systems.

Why does uploading a new .htaccess file cause a '500 Internal Server Error'?

An HTTP 500 error almost always stems from unsupported directives: (1) your Apache server does not have the required modules enabled (such as `mod_rewrite` or `mod_headers`), or (2) the primary `httpd.conf` server configuration has `AllowOverride None` set instead of `AllowOverride All`. Always test changes in a staging environment and keep a backup of the original file.

Can I use .htaccess directives on an Nginx or Caddy web server?

No. Nginx deliberately does not read .htaccess files for performance and concurrency reasons. Reading per-directory configuration files requires disk I/O on every single HTTP request. Use the 'Nginx' tab in our generator to produce native `server { ... }` block configuration directives for your `/etc/nginx/sites-available/` directory.

What is the difference between a 301 Permanent and a 302 Temporary redirect?

An HTTP 301 redirect signals a permanent resource relocation and transfers 90% to 99% of link ranking equity (PageRank) from the old URL to the new destination. An HTTP 302 redirect signals a temporary change, causing search engines to retain the original URL in the index without transferring link equity.

Why is blocking dotfiles (.env, .git, .htaccess) critical for cybersecurity?

Dotfiles like `.env` and `.git` contain severe vulnerabilities: database credentials, private API keys, JWT signing secrets, and complete git repository commit history. Attackers run automated web vulnerability scans seeking exposed `.env` files. Adding explicit denial directives in `.htaccess` guarantees that attempts to request these files receive an immediate HTTP 403 Forbidden.

What do the Apache flags [R=301,L,NE] signify in RewriteRule directives?

The `[R=301]` flag instructs Apache to issue an HTTP 301 Moved Permanently status code. The `[L]` (Last) flag tells the rewrite engine to stop evaluating subsequent rewrite rules for this request. The `[NE]` (NoEscape) flag prevents Apache from converting special characters (like query ampersands) into percent-encoded entities.

How does canonical domain normalization (www vs. non-www) prevent SEO duplication?

Search engines consider `https://example.com` and `https://www.example.com` to be two entirely distinct hostnames. If both hostnames serve the same content without redirection, search engines split ranking authority and may penalize the site for duplicate content. Enforcing a single canonical domain consolidates all backlink equity.

What is HSTS Preload and when should I activate it?

HTTP Strict Transport Security (HSTS) with the `preload` directive instructs browsers to hardcode your domain into Google Chrome, Apple Safari, and Mozilla Firefox preload lists. Once preloaded, browsers refuse to connect to your domain over unencrypted HTTP under any circumstances, neutralizing SSL-stripping man-in-the-middle attacks.

Need Automated Continuous Audits?

Upgrade from Single-Check to Automated DAST Vulnerability Scanner

Full-scale active fuzzing for OWASP Top 10, SQLi, XSS, SSRF & BOLA. Scale with automated schedules, Slack alerts, 150+ monthly credits, and compliance PDF exports on our paid tiers.

Headless Chromium SPA crawlerActive OWASP Top 10 fuzzingAutomated SQLi & XSS verification

Strengthen Your Server & Search Foundation

WeSecureX provides free, privacy-first developer utilities to audit response headers, test SSL cipher health, and prevent data exposure.