.htaccess Tips and Tricks

Date: 2024-12-28 | 2 min read | 356 words

So, you've got your website up and running, it looks great and it's super fast but you're being bugged by those pesky file extensions on your URLs. Or you changed some pages around and now you need to redirect the old links. Here's a quick post on some neat little tricks to control your website using the mythical .htaccess file. 🫨

What is the .htaccess file?

.htaccess is a config file used in Apache-based web servers. In a shared hosting environment, it's used to be able to configure some of the settings that would normally be found in the main configuration files, which most people don't have access to with a normal web host.

Note that syntax is very important or you can break access to your site. Also, this post applies to people running their website in an Apache stack (LAMP), not nginx (LEMP). Also note that mod_rewrite must be enabled by your hosting provider

"Clean" URLs

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Force HTTPS

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

301 Redirects - Pages

Redirect 301 /oldpage.html https://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html https://www.yoursite.com/folder/

301 Redirects - Entire Site

Redirect 301 / https://newsite.com/

Only allow certain IP addresses to access

# Require all denied
# Require ip xxx.xxx.xxx.xxx

Disable directory browsing on your server

Options All -Indexes

Enable directory browsing on your server

Options All +Indexes

Disable hotlinking of your images

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

Redirect hotlinks of your images to a specified image

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?your-website.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ https://www.your-website.com/do-not-hotlink-our-content.jpg [R,L]

Custom 404, 401 and 500 error message pages

ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 https://error.yourdomain.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

Redirect users to a maintenance page

ErrorDocument 403 YourMaintenancePageFilenameOrFullUrlUrl.html
Order deny,allow
Deny from all
Allow from 555.555.555.555

If you're running an old-school website on a shared host, this should hopefully help you take your site to the next level.

← Oh hi thereall postsMinecraft is always there →