The .htaccess file is a powerful configuration file used by web servers to control the behavior of websites. It can be used to perform a wide range of functions, including URL redirection, password protection, caching, and more. While .htaccess files are widely used, many website owners and developers are unaware of the full range of capabilities they offer.
In this article, we will explore 21 .htaccess tricks that everyone should know. From creating custom error pages to blocking bad bots and optimizing website performance, these tips will help you get the most out of your .htaccess file. Whether you’re a beginner or an experienced web developer, these tricks will help you improve your website’s functionality and security, making it a better experience for your visitors. So, let’s get started!
- Redirect non-www to www
One of the most common uses of .htaccess is to redirect non-www URLs to www URLs (or vice versa). This can help improve SEO and ensure that all traffic to your site is directed to a single domain. Here’s an example:
123RewriteEngine onRewriteCond %{HTTP_HOST} !^www\.RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] - Redirect HTTP to HTTPS
Another common use of .htaccess is to redirect HTTP URLs to HTTPS URLs to ensure that all traffic to your site is encrypted. Here’s an example:
123RewriteEngine OnRewriteCond %{HTTPS} offRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] - Block IP addresses
You can use .htaccess to block specific IP addresses or ranges of IP addresses from accessing your site. This can be useful for blocking malicious traffic or spam. Here’s an example:
12Order deny,allowDeny from 123.45.67.89 - Password protect a directory
You can use .htaccess to password-protect a directory on your website. This can be useful for restricting access to sensitive content or areas of your site. Here’s an example:
1234AuthType BasicAuthName "Restricted Area"AuthUserFile /path/to/password/fileRequire valid-user - Block hotlinking
Hotlinking is the practice of linking to images or other content on your site from another website. This can increase bandwidth usage and decrease site performance. You can use .htaccess to block hotlinking and prevent others from stealing your content. Here’s an example:
1234RewriteEngine onRewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/.*$ [NC]RewriteRule \.(gif|jpg|jpeg|png|bmp)$ - [F] - Customize error pages
You can use .htaccess to customize the error pages that are displayed when a user encounters a 404 or other error on your site. Here’s an example:
1ErrorDocument 404 /errors/404.html - Enable gzip compression
You can use .htaccess to enable gzip compression on your website to reduce the size of files that are transmitted to users’ browsers. Here’s an example:
1234567891011<IfModule mod_deflate.c>AddOutputFilterByType DEFLATE text/plainAddOutputFilterByType DEFLATE text/htmlAddOutputFilterByType DEFLATE text/xmlAddOutputFilterByType DEFLATE text/cssAddOutputFilterByType DEFLATE application/xmlAddOutputFilterByType DEFLATE application/xhtml+xmlAddOutputFilterByType DEFLATE application/rss+xmlAddOutputFilterByType DEFLATE application/javascriptAddOutputFilterByType DEFLATE application/x-javascript</IfModule> - Disable directory browsing
You can use .htaccess to disable directory browsing on your website to prevent users from accessing the contents of directories that do not contain an index file. Here’s an example:
1Options -Indexes - Set caching headers
You can use .htaccess to set caching headers for your website to improve performance and reduce bandwidth usage. Here’s an example:
12345678910<IfModule mod_expires.c>ExpiresActive OnExpiresByType text/css "access plus 1 week"ExpiresByType text/javascript "access plus 1 week"ExpiresByType application/javascript "access plus 1 week"ExpiresByType image/gif "access plus 1 month"ExpiresByType image/png "access plus 1 month"ExpiresByType image/jpeg "access plus 1 month"ExpiresByType image/x-icon "access plus 1 year"</IfModule> - Redirect a single page
You can use .htaccess to redirect a single page on your website to another page or URL. This can be useful if you have updated the location of a page or if you want to redirect traffic from a specific page to another page. Here’s an example:
1Redirect 301 /old-page.html https://www.example.com/new-page.html - Limit file types
You can use .htaccess to limit the types of files that can be uploaded to your website. This can help prevent users from uploading malicious files or files that could be used to compromise your website. Here’s an example:
1234<FilesMatch "\.(php|pl|py|jsp|asp|sh|cgi)$">Order allow,denyDeny from all</FilesMatch> - Enable server-side includes
You can use .htaccess to enable server-side includes on your website. This allows you to include common elements, such as headers and footers, on multiple pages without having to update each page individually. Here’s an example:
123Options +IncludesAddType text/html .shtmlAddHandler server-parsed .shtml - Set default index page
You can use .htaccess to set the default index page for directories on your website. This allows you to specify which file should be displayed when a user navigates to a directory that does not contain an index file. Here’s an example:
1DirectoryIndex index.php index.html - Prevent file access
You can use .htaccess to prevent users from accessing specific files or file types on your website. This can be useful for protecting sensitive files, such as configuration files or database backups. Here’s an example:
1234<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|sql)$">Order deny,allowDeny from all</FilesMatch> - Set PHP options
You can use .htaccess to set PHP options for your website. This allows you to configure various aspects of PHP, such as memory limits, file upload sizes, and error reporting. Here’s an example:
123php_value memory_limit 256Mphp_value upload_max_filesize 64Mphp_value error_reporting E_ALL - Rewrite URLs
You can use .htaccess to rewrite URLs on your website to make them more user-friendly or to change the structure of your site. Here’s an example:
12RewriteEngine OnRewriteRule ^blog/([^/\.]+)/?$ blog.php?id=$1 [L] - Allow access from specific IP addresses
You can use .htaccess to allow access to your website from specific IP addresses or ranges of IP addresses. This can be useful if you want to restrict access to your site to a specific group of users. Here’s an example:
123Order deny,allowDeny from allAllow from 123.45.67 - Force HTTPS
You can use .htaccess to force your website to use HTTPS instead of HTTP. This is important for security reasons, as HTTPS encrypts data between the user’s browser and the web server. Here’s an example:
123RewriteEngine OnRewriteCond %{HTTPS} offRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L] - Add custom error pages
You can use .htaccess to add custom error pages to your website. This allows you to provide a more user-friendly and professional-looking error page for your visitors. Here’s an example:
12ErrorDocument 404 /404.htmlErrorDocument 500 /500.html - Set server signature
You can use .htaccess to set the server signature for your website. The server signature is a string that identifies the web server software running on your site. By default, Apache includes the server signature in the response headers, which can give attackers information about your server. Here’s an example:
1ServerSignature Off - Bock bad bots
Create a list of user agents: Bots identify themselves using a user agent string. You can create a list of user agents to block in your .htaccess file. Here’s an example:
12345RewriteEngine OnRewriteCond %{HTTP_USER_AGENT} badbot1 [NC,OR]RewriteCond %{HTTP_USER_AGENT} badbot2 [NC,OR]RewriteCond %{HTTP_USER_AGENT} badbot3RewriteRule ^(.*)$ - [F,L]In this example, we’re using the RewriteCond directive to check if the HTTP_USER_AGENT header matches one of our bad bots. If it does, we use the RewriteRule directive to return a 403 Forbidden error.
Conclusion
.htaccess is a powerful tool for configuring and securing your website. In this article, we’ve looked at 20 real-world examples of .htaccess that you can use to improve the functionality, security, and performance of your website. Whether you’re a beginner or an experienced developer, there’s something here for everyone. By following these best practices, you can ensure that your website is optimized for search engines, protected against attacks, and provides a great user experience for your visitors.