· Technology · 2 min read
Apache Webserver .htaccess File Tips and Tricks
Useful Apache .htaccess directives for URL rewriting, access control, caching, and security hardening.

Place a site offline with the exception of a particular static IP address
# Turn Rewrite Engine On. Requires Apache Rewrite module.
RewriteEngine on
# IP Address to *not* redirect. Multiple lines like this are allowed.
RewriteCond %{REMOTE_ADDR} !^192\.168\.1\.1
# Prevent infinite loop.
RewriteCond %{REQUEST_URI} !/offline.html$ [NC]
# The URL to send all traffic to.
RewriteRule .* http://www.yourdomain.com/offline.html [R=302,L]Redirect all web traffic from http:// (port 80) to https:// (secure - port 443)
# Turn Rewrite Engine On. Requires Apache Rewrite module.
RewriteEngine On
# If HTTPS is off
RewriteCond %{HTTPS} off
# Then rewrite our URL from http:// to https://
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]Redirect all web traffic from http://www.olddomain.com to http://www.newdomain.com while preserving the remainder of the URL path
# Turn Rewrite Engine On. Requires Apache Rewrite module.
RewriteEngine On
RewriteBase /
# If our URL is www.olddomain.com or olddomain.com
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
# Then redirect to www.newdomain.com, while preserving the remainder of the URL path
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]Redirect a URL which is really just a query string — Useful for WordPress page redirects
# Turn Rewrite Engine On. Requires Apache Rewrite module.
RewriteEngine On
RewriteBase /
# If our url is http://www.domain.com/?page_id=12
RewriteCond %{QUERY_STRING} ^page_id=12$
# Then redirect to our new url
RewriteRule ^$ http://www.newdomain.com/page.html? [R,L]For WordPress websites, block access to wp-admin.php and xmlrpc.php except for a static IP address
RewriteCond %{REQUEST_URI} ^(.*)wp-login\.php(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)wp-admin$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)xmlrpc\.php$
# Change this IP address to your static IP address.
RewriteCond %{REMOTE_ADDR} !^192\.168\.1\.1$
# You will need to create a simple HTML file with your special message called denied.html
RewriteRule .* denied.html [R=302,L]- apache
- linux
- webserver
Share: