Five practical .htaccess tricks

30 Nov, 2018

Apache's '.htaccess' has some very powerful tools that you can use with minimal effort to enhance the user experience and even performance, of your website. These are the top 5 .htaccess tricks that you should add to your website today.

1. Redirecting users to your maintenance page. If you're making some big changes to your site that could affect users negatively, you may want to temporarily redirect them to a maintenance page while you make the changes.


RewriteEngine On
RewriteBase /

# Allow your IP
RewriteCond %{REMOTE_ADDR} !^000\.000\.000\.000

# Redirect to maintenance.html
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ http://example.com/maintenance.html [R=307,L]
		

2. Enabling gzip compression to reduce the time it takes your website to load.


# Compression
SetOutputFilter DEFLATE
SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip
		

3. Blocking bad IP addresses.


# Block some IP 000.000.000.000
RewriteCond %{REMOTE_HOST} 000.000.000.000 [OR]
		

4. Specify custom HTTP error pages to create a better user experience in the event of a broken link or some other error.


# Custom error pages
ErrorDocument 400 /error/400.html
ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html
		

5. Remove .html and .php extensions to shorten URLs and make them less confusing to users.


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
# Remove .php extention
RewriteRule ^([^\.]+)$ $1.php [NC,L]
# Remove .html extention
RewriteRule ^([^\.]+)$ $1.html [NC,L]
		

Other Tutorials

View All

Building a custom chromecast web app

html - javascript


Chromecasts make streaming your favourite songs, games and movies easy. But if you're like me, you might be wondering what's going on behind the scenes when you cast an app, and how you can build your own.

Immersive Parallax scrolling effect

javascript - css - html


You might have noticed while moving along in a car or train, how far away objects seem to move across your vision slower than those closer to your eyes. This effect is known as parallax and its a fundamental aspect of vision which can often go unnoticed.

Detecting system dark mode in CSS

css


The "dark mode" feature has been spreading to apps and websites far and wide recently. It brings a new and discrete look to your applications as well as offering some extra control to the user...