.htaccessRedirectsSecurity5 min read

Configure .htaccess for your site

301/302 redirects, custom error pages, IP blocking, hotlink protection and URL rewriting.


What is .htaccess?

The .htaccess file is an Apache/LiteSpeed configuration file that allows you to control server behavior at the directory level. It is located in public_html/ and affects the entire site.

Redirects

301 redirect (permanent)

apache
# Redirect a specific page
Redirect 301 /old-page https://yourdomain.com/new-page

# Redirect with RewriteRule
RewriteEngine On
RewriteRule ^blog/old-article$ /blog/new-article [R=301,L]

302 redirect (temporary)

apache
Redirect 302 /maintenance https://yourdomain.com/coming-soon

Redirect entire domain

apache
RewriteEngine On
RewriteCond %{HTTP_HOST} ^old-domain\.com$ [NC]
RewriteRule ^(.*)$ https://new-domain.com/$1 [R=301,L]

Force www or non-www

apache
# Force www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# Force non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Custom error pages

apache
# Custom errors
ErrorDocument 404 /errors/404.html
ErrorDocument 403 /errors/403.html
ErrorDocument 500 /errors/500.html
ErrorDocument 503 /errors/503.html

Block IPs

apache
# Block specific IPs
<RequireAll>
  Require all granted
  Require not ip 192.168.1.100
  Require not ip 10.0.0.0/8
</RequireAll>

# Alternative syntax (Apache 2.2)
Order Allow,Deny
Allow from all
Deny from 192.168.1.100

Hotlink protection

Prevent other sites from using your images directly:

apache
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp|svg)$ - [F,NC,L]

Security headers

apache
<IfModule mod_headers.c>
  # Prevent clickjacking
  Header always set X-Frame-Options "SAMEORIGIN"
  
  # Prevent MIME sniffing
  Header always set X-Content-Type-Options "nosniff"
  
  # XSS Protection
  Header always set X-XSS-Protection "1; mode=block"
  
  # Referrer Policy
  Header always set Referrer-Policy "strict-origin-when-cross-origin"
  
  # Permissions Policy
  Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
</IfModule>

Disable directory listing

apache
# Prevent folder contents from being visible without an index file
Options -Indexes

Protect sensitive files

apache
# Block access to configuration files
<FilesMatch "^\.(htaccess|htpasswd|env)$">
  Require all denied
</FilesMatch>

# Block access to wp-config.php
<Files wp-config.php>
  Require all denied
</Files>

Recommendations

  • Always back up .htaccess before editing it
  • Test changes immediately after saving
  • If the site returns error 500, check the file syntax
  • Use comments (#) to document each rule
  • Do not duplicate RewriteEngine On (only once at the top)

Was this guide helpful?