Giacomo Balli profile picture
Giacomo Balli
The Mobile Guy

Advisor | Consultant | Entrepreneur
Over a decade of mobile experience at your service.
I help business owners navigate and leverage technology.

Let's Chat

htaccess

.htaccess is a file used by an Apache webserver to manage access.

.htaccess tester


.htaccess variables

The strength of using .htaccess is that it gives you many variables you can use to create your own customized behavior.
Assuming your URL is https://domain1.com/test.php?user=joe, here are the most common ones, assuming your :

.htaccess flags

Flags are used to provide additional customization for your rules. Here are the most common ones:

.htaccess Rewrite and Redirection Rules

The most common use case for .htaccess is to handle URL rewrites and redirecting to different pages.
Remember you need to set RewriteEngine on as very first line.

Serve All Requests With One PHP File with .htaccess

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]

Force www with .htaccess

RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]

Force HTTPS with .htaccess

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

Remove Trailing Slash with .htaccess

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

Redirect a Single Page with .htaccess

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

Redirect an Entire Site with .htaccess

Redirect 301 / https://newsite.com/

.htaccess for Security

Your .htaccess file can also be used to implement security features.

Deny Bot access with .htaccess

RewriteCond %{HTTP_USER_AGENT} ^\-?$                                                              [OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|%00).*                            [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(HTTrack|clshttp|archiver|loader|email|nikto|miner|python).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|libwww\-perl|curl|wget|harvest|scan|grab|extract).* [NC]
RewriteRule ^(.*)$ - [F,L]

Deny Access to Hidden Files and Directories with .htaccess

RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]

Disable Directory Browsing with .htaccess

Options All -Indexes

Disable Image Hotlinking with .htaccess

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

.htaccess for Performance

Your .htaccess file can also be used to implement performance features.

Compress files with .htaccess

<IfModule mod_gzip.c>
  mod_gzip_on       Yes
  mod_gzip_dechunk  Yes
  mod_gzip_item_include file      \.(html?|txt|css|log|js|php|pl)$
  mod_gzip_item_include handler   ^cgi-script$
  mod_gzip_item_include mime      ^text/.*
  mod_gzip_item_include mime      ^application/x-javascript.*
  mod_gzip_item_exclude mime      ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

Set cache expiration policy with .htaccess

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 7 days"
  
 # Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/webm "access plus 1 year"
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # Fonts
  ExpiresByType font/ttf "access plus 1 year"
  ExpiresByType font/otf "access plus 1 year"
  ExpiresByType font/woff "access plus 1 year"
  ExpiresByType font/woff2 "access plus 1 year"
  ExpiresByType application/font-woff "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Others
  ExpiresByType application/pdf "access plus 1 month"
  ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
</IfModule>

Limit Upload File Size with .htaccess

LimitRequestBody 1048576

Miscellaneous .htaccess directives

Finally, some additional directives you can use to further customize your server.

Custom Error Pages with .htaccess

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

Force Downloading with .htaccess

<Files *.zip>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

Hide Server Info (Server Signature) with .htaccess

ServerSignature Off

Set Server Timezone with .htaccess

SetEnv TZ America/Los_Angeles

Multisite .htaccess

If you're using Apache with multiple virtualhosts (ie one server hosting multiple domains), you might have wondered how to use a single htaccess file.
This is can easily be done by placing the htaccess file in the parent folder instead of the usual domain root folder.

For example, if your different website files are stored in /var/www/domain1.com/public_html, /var/www/domain2.com/public_html etc, rather than having an htaccess file in every public_html folder you can simply create a "master" htaccess file and place it in /var/www/.
Just remember you will now need to account for a different root.

For example this:

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

will need to written as:
Redirect 301 /domain1.com/public_html/oldpage.html https://www.domain1.com/newpage.html



#htaccess
Published: Sat, May 15 2021 @ 10:37:34
Back to Blog