Web Server Redirects, URL Rewrites & Security Headers Production Runbook
A definitive production engineering runbook for configuring web server URL redirection, canonical routing, and defense-in-depth HTTP security headers. Master Apache mod_rewrite directives, Nginx return vs rewrite performance semantics, strict HSTS preloading, Content-Security-Policy (CSP 3), and zero-trust header architecture.
1. URL Redirection Architecture: 301, 302, 307 & 308 Semantics in Modern SEO
# Inspect HTTP response status code, Location header, and redirect hops
curl -ILs -o /dev/null -w "Status: %{http_code} | Hops: %{num_redirects} | Target: %{url_effective}\n" https://example.com/old-page
# Verify that POST request method and payload are preserved across a 308 redirect
curl -s -o /dev/null -w "%{http_code}\n" -X POST -d '{"event":"checkout"}' -H "Content-Type: application/json" -L https://example.com/api/v1/eventUses curl with -I and -L flags to trace redirect headers, verify hop counts, and validate HTTP verb preservation.
| Status Code | Permanence | Link Equity Transferred | HTTP Method Preservation | Primary Production Use Case | Copy |
|---|---|---|---|---|---|
| 301 Moved Permanently | Permanent | Yes (~95% - 99%) | May mutate POST to GET | Domain migration, permalink restructure, non-www to www | |
| 302 Found (Legacy) | Temporary | No link equity transfer | May mutate POST to GET | Maintenance pages, seasonal promotional banners | |
| 307 Temporary Redirect | Temporary | No link equity transfer | Guaranteed method preservation | Form submission processing, temporary geo-routing | |
| 308 Permanent Redirect | Permanent | Yes (~95% - 99%) | Guaranteed method preservation | Modern REST/GraphQL API version migrations |
2. Apache mod_rewrite Anatomy & .htaccess Performance Optimization
<VirtualHost> or <Directory> containers in httpd.conf to eliminate per-request filesystem stat calls.
2. Order Specific Rules Before Catch-Alls: mod_rewrite evaluates rules sequentially from top to bottom. Specific page-to-page 301 redirects must precede broad regular expression pattern matches.
3. Use the L (Last) Flag: Always append [L] to terminal redirect rules to instruct mod_rewrite to stop evaluating subsequent rules immediately.
4. Manage Query Strings Defensively: By default, mod_rewrite appends original query strings. Use the [QSA] (Query String Append) flag when merging new parameters, or append a trailing question mark (?) to the target to strip unwanted query strings entirely.# Enable Apache Rewrite Engine
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# 1. Force HTTPS protocol
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 2. Redirect non-www to canonical www domain
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 3. Individual page 301 with query string preservation
RewriteRule ^legacy-pricing\.html$ /pricing/ [R=301,L,QSA,NC]
</IfModule>Production Apache mod_rewrite snippet enforcing HTTPS, canonical domain routing, and clean 301 page redirects.
| Rewrite Flag | Full Directive Name | Operational Behavior | Best Practice Recommendation | Copy |
|---|---|---|---|---|
| [R=301] | Redirect=301 | Issues 301 Moved Permanently header | Always specify explicit status code (defaults to 302 if omitted) | |
| [L] | Last | Halts rule processing for current pass | Essential on terminal redirects to prevent duplicate rule execution | |
| [NC] | NoCase | Case-insensitive pattern matching | Use for URLs that may be entered in mixed casing | |
| [QSA] | Query String Append | Combines old and new query strings | Mandatory when preserving analytics tags like utm_source |
3. Nginx High-Performance Routing: Why return 301 Beats rewrite
# Fast HTTP to HTTPS redirection server block (Zero regex overhead)
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
# Canonical domain enforcement and path rewrites inside HTTPS block
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
# Exact location match for single page redirect
location = /old-checkout {
return 301 /checkout/;
}
# Regex rewrite for directory migration
rewrite ^/v1/docs/(.*)$ /docs/$1 permanent;
}Nginx configuration demonstrating instantaneous return 301 redirection alongside regex rewrite directives.
| Directive | Execution Phase | PCRE Regex Engine | Performance Overhead | Recommended Application | Copy |
|---|---|---|---|---|---|
| return 301 <url> | NGX_HTTP_SERVER_REWRITE_PHASE | Disabled (Instant string interpolation) | Lowest (~0.02ms latency) | Global HTTPS enforcement, canonical domain routing | |
| rewrite <regex> <target> permanent | NGX_HTTP_REWRITE_PHASE | Enabled (PCRE evaluation) | Moderate (~0.15ms latency) | Dynamic path transformations with regex captures | |
| try_files $uri $uri/ =404 | NGX_HTTP_CONTENT_PHASE | Filesystem stat checks | Low (~0.05ms) | Single Page Applications (Vue / React / Astro) | |
| proxy_pass <backend> | NGX_HTTP_CONTENT_PHASE | Upstream socket forwarding | Variable (Backend bound) | Reverse proxying to Node.js, Go, Python backends |
4. Defense-in-Depth Security Headers: HSTS Preload, Clickjacking & CSP 3
<iframe> elements. Set to DENY or SAMEORIGIN.
4. X-Content-Type-Options: Set to nosniff to prevent browsers from MIME-sniffing a text/plain upload into an executable JavaScript payload.
5. Permissions-Policy: Explicitly disables sensitive browser hardware features (such as camera, microphone, and geolocation) across third-party embedded scripts. Generate complete production header bundles with our HTTP Security Headers & HSTS Generator.# Enterprise-Grade Security Headers (A+ Rating on SecurityHeaders.com)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;Complete Nginx security header suite achieving maximum A+ security ratings across automated scanners.
| Security Header | Primary Threat Mitigated | Recommended Production Value | Risk if Omitted | Copy |
|---|---|---|---|---|
| Strict-Transport-Security | Man-in-the-Middle (MITM) & SSL stripping | max-age=63072000; includeSubDomains; preload | Unencrypted initial connection vulnerable to packet interception | |
| Content-Security-Policy | Cross-Site Scripting (XSS) & data exfiltration | default-src 'self'; script-src 'self'; object-src 'none' | Arbitrary third-party JavaScript execution in user sessions | |
| X-Frame-Options | Clickjacking & UI redressing attacks | DENY (or SAMEORIGIN) | Attacker can embed page in transparent iframe to capture clicks | |
| X-Content-Type-Options | MIME-type sniffing & drive-by exploits | nosniff | Browser executes disguised non-script files as JavaScript |
5. Web Server Configuration Syntax & Header Directives Cheatsheet
# Verify presence of all defensive security headers
curl -sI https://example.com | grep -iE "(strict-transport|content-security|x-frame|x-content-type|referrer-policy|permissions-policy)"Grep filter extracting all active security headers from the server response headers.
| Directive / Task | Apache (.htaccess) | Nginx (nginx.conf) | Caddy (Caddyfile) | Cloudflare (_headers) | Copy |
|---|---|---|---|---|---|
| 301 Permanent Redirect | Redirect 301 /old /new | return 301 /new; | redir /old /new permanent | N/A (Managed via Page Rules / Bulk Redirects) | |
| Force HTTPS | RewriteCond %{HTTPS} off ... | return 301 https://$host$request_uri; | Automatic HTTPS by default | Always Use HTTPS toggle in Cloudflare Dashboard | |
| Set Security Header | Header always set Name "Value" | add_header Name "Value" always; | header Name "Value" | Name: Value | |
| Custom 404 Error Page | ErrorDocument 404 /404.html | error_page 404 /404.html; | handle_errors { ... } | /404.html status 404 |
Related Free Online Tools
Put these techniques into practice immediately with our privacy-first browser utilities:
Generate instant Apache .htaccess and Nginx 301/302 redirects, HTTPS rewrites, and canonical rules.
Build and validate strict, injection-proof Content-Security-Policy header rules visually.
Configure HSTS preload, X-Frame-Options, and Permissions-Policy blocks across all web servers.