Master Apache Useful .htaccess tips & tricks

.htaccess is just not file extension rather a powerful control center to manage Web Server configurations that makes life very easy specially for web hosting companies. From Authorization/Authentication to URL rewriting, Server side includes (SSI) to Directory Listing, Customized error handling to Cache control & managing MIME type, everything can be controlled from this file and that even without restarting web server.

On top of it, .htaccess files affect the directory they are placed in and all sub-directories.

In this blog, we share practical and tested .htaccess examples for modern web development, SEO, and performance optimization.

URL Rewriting and Extension Hiding

Hiding webpage extensions & redirecting
RewriteEngine On
RewriteCond %{THE_REQUEST} s/+(.+).php[s?] [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,QSA,L]

Redirects for SEO Canonicalization

Redirecting non-www to www version
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$ RewriteRule ^(.*)$ "http://www.example.com/$1" [R=301,L]
Redirect the site IP address (A.B.C.D) to the domain name
RewriteCond %{HTTP_HOST} ^A.B.C.D$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Redirect Subdomains or Folders

 

Serve content from a different server or host or sub-domain as a subfolder without redirection
RewriteRule ^/subdomain/(.*) http://subdomain.example.com/$1 [P]
ProxyPassReverse  /subdomain/ http://subdomain.example.com/

Cache Control for Performance

Control caching
# Caching for 1 Year
<FilesMatch ".(ico|svg|woff|eot|ttf)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

# Caching for 1 Week
<FilesMatch ".(jpg|png|gif|css|js)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>

Defining MIME types for different file type
<IfModule mod_mime.c>
    AddType application/javascript          js
    AddType application/vnd.ms-fontobject   eot
    AddType application/x-font-ttf          ttf ttc
    AddType font/opentype                   otf
    AddType application/x-font-woff         woff
    AddType image/svg+xml                   svg svgz 
    AddEncoding gzip                        svgz
</IfModule>

Enable GZIP compression

Reduce file size for faster load times:

<IfModule mod_deflate.c>
<FilesMatch ".(html|php|txt|xml|js|css)$">
SetOutputFilter DEFLATE
</FilesMatch>
</IfModule>

Maintenance Mode

Show a static maintenance page to users, but allow admin access:
#Allowing only admin website
RewriteCond %{REQUEST_URI} !^/admin/ [NC]
RewriteCond %{REQUEST_URI} !((.*).css|(.*).js|(.*).jpg|(.*).gif|(.*).png) [NC]
RewriteRule ^(.*)$ /ErrorPages/UnderMaintenence.html [NC,L,U,QSA]
Force lowercase urls
RewriteMap lowercase int:tolower
RewriteCond $1 [A-Z]
RewriteRule ^((.*).html|(.*).htm|(.*).asp|(.*).aspx|(.*).ashx|(.*).php)$ ${lowercase:$1} [R=301,L]

Security Best Practices

Block external access to sensitive files
#  Block external access to the httpd.ini and httpd.parse.errors files
RewriteRule ^/httpd(?:.ini|.parse.errors).*$ / [NC,F,O]
#  Block external access to the Helper ISAPI Extension
RewriteRule ^.*.isrwhlp$ / [NC,F,O]
Prevent Directory Listing
Options -Indexes
Set external redirection map file
# Set redirection map
RewriteMap siterewritemap txt:rewrite-map.txt
RewriteMap lower int:tolower

# Use redirection map
RewriteCond %{QUERY_STRING} ^(.+)
RewriteCond ${siterewritemap:${lower:%{REQUEST_URI}}?${lower:%{QUERY_STRING}}} (.+) [NC]
RewriteRule .* %2 [NC,L,R=301]

Allow cross-domain Web fonts

Fix CORS issues for fonts hosted on CDNs or subdomains:

<FilesMatch ".(ttf|ttc|otf|eot|woff)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>
Allow resources like fonts, js and css to be loaded from sub-domain strictly
SetEnvIf Origin "http(s)?://(.+.)?(example.com)$" ORIGIN_DOMAIN=$0
<IfModule mod_headers.c>
    <FilesMatch ".(eot|font.css|otf|ttc|ttf|woff|js|png|jpg|jpeg|gif)$">
        Header set Access-Control-Allow-Origin %{ORIGIN_DOMAIN}e env=ORIGIN_DOMAIN
    </FilesMatch>
</IfModule>

Try playing around htaccess rules using http://htaccess.madewithlove.be/

Final Tips

  • Test .htaccess rules on a staging server before deploying.
  • Use htaccess tester tools like if needed.
  • Keep a backup of the original file.
  • Avoid overly complex or nested rules to maintain performance.
(Visited 378 times, 1 visits today)