.htaccess File- What is .htaccess?
A .htaccess file is a directory-level configuration file used by Apache-based web servers to control various website functions at the directory and subdirectory level.
- Capabilities of .htaccess
With .htaccess, you can manage redirects, protect confidential sections of your site, customize error pages, specify directory listings, and adjust caching rules, among other things.
- Why use .htaccess?
It provides a fast and convenient way to make changes to the server configurations without the need to alter server configuration files or restart the server.
(https://royalhost.net/blog/wp-content/uploads/2023/06/htaccess.webp)
Common Uses of .htaccess:- Control the behavior of your site with
RewriteRules for clean URLs and redirections.
- Password protect specific directories using
AuthType, AuthName, AuthUserFile, and Require directives.
- Display custom error pages using the
Errordоcument directive (e.g., Errordоcument 404 /notfound.html).
- Prevent directory listing by setting
Options -Indexes.
- Manage file caching to improve site performance with
ExpiresByType and Header directives.
- Add or override any MIME types as per your site's requirements.
Cautions When Using .htaccess:It's important to remember that incorrectly configuring a .htaccess file can cause errors on your website. Always make sure to backup your .htaccess file before making any changes and test extensively.
Advanced Features of .htaccess.htaccess files allow you to control many aspects of your website with an incredible level of granularity. Here are additional features you might find useful:
Denying/Allowing IP AddressesYou can block or allow traffic to your website based on IP addresses.
Order Deny,Allow
Deny from all
Allow from 123.456.789.000
Changing Upload LimitsFor sections of your site where file uploads are necessary, like image galleries, you can increase the maximum size for file uploads:
php_value upload_max_filesize 20M
php_value post_max_size 20M
Preventing Hotlinking of Your ContentHotlinking occurs when other sites link directly to the images or other files on your site, using your server's bandwidth to serve files.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
SEO: Redirecting WWW and Non-WWW URLsSearch engines see "www.example.com" and "example.com" as separate websites. To avoid duplicate content penalties:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
Or reverse, to remove the 'www':
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
Setting Server Time ZoneYou can set the preferred time zone directly from .htaccess:
SetEnv TZ America/Los_Angeles
Custom File TypesSometimes, you may need to serve different content types that aren't configured on the server by default:
AddType application/x-httpd-php .phtml .php5
This would process files with extensions ".phtml" or ".php5" as PHP files.
Handling Character Sets and EncodingYou can manage character encodings to ensure text is displayed correctly:
AddDefaultCharset UTF-8
When writing rules and deploying changes through .htaccess:
- Always back up the current .htaccess before making changes.
- Do changes incrementally and test functionality to pinpoint errors easily.
- Remember that some hosting environments might have specific configurations or limitations.
Note: An incorrect .htaccess file can cause a 500 Internal Server Error. If this happens, either revert to a backup or correct the syntax errors.Further Advanced .htaccess Techniques and Use CasesSetting Custom PHP ValuesIf you're using PHP, `.htaccess` allows you to change the values of certain PHP directives for your hosting environment.
php_value memory_limit 256M
php_value upload_max_filesize 10M
php_value max_execution_time 300
However, keep in mind that for this to work, your server must be running PHP as an Apache module.
Securing Sensitive FilesYou can add extra protection to sensitive files like `wp-config.php`, `.env`, or even the `.htaccess` file itself:
<Files wp-config.php>
order allow,deny
deny from all
</Files>
Forcing HTTPSRedirect users to HTTPS to ensure encrypted connections. This is especially crucial after the advent of HTTP/2.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Blocking User AgentsSome webmasters might want to block certain web crawlers or user agents.
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} BadBot [NC,OR]
RewriteCond %{HTTP_USER_AGENT} AnotherBadBot [NC]
RewriteRule ^.* - [F,L]
Replace `BadBot` and `AnotherBadBot` with the actual user agent strings you want to block.
GZIP CompressionImprove loading times by compressing files with mod_deflate if supported by your server:
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json
Handling CORS (Cross-Origin Resource Sharing)The following rule can help you to allow cross-domain AJAX requests to your site:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Change `*` to a specific domain to restrict access only to that domain.
Implementing Cache-ControlOptimize browser caching by specifying cache-control headers:
<filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
Blocking File IncludesPrevent direct access to file types, which should not be directly accessed in the browser, such as configuration files:
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>
Leveraging ETagsConfigure ETags to handle browser caching validation, which can enhance performance by more efficiently determining whether a file has changed.
FileETag MTime Size
Before using these examples, it's important to:
- Understand that changes made in `.htaccess` can have a widespread impact.
- Make sure that `mod_rewrite`, `mod_headers`, and other necessary Apache modules are enabled on your server.
- Test any changes on a development copy of your site before pushing to production.
Advanced Mod_Rewrite TechniquesRewriteMapIf you need more complex or dynamic rewriting rules, `RewriteMap` creates a key-value map that can be used in the rewriting process. This is defined in the server configuration file (httpd.conf or apache2.conf) and cannot be declared in `.htaccess`.
# In httpd.conf
RewriteMap lowercase int:tolower
Then in `.htaccess`, you can use it like this:
RewriteRule ^(.*)$ ${lowercase:$1} [R,L]
RewriteLockWhen using `RewriteMap` in a threaded environment, you might need to set up `RewriteLock` to serialize access to the map and prevent race conditions.
# In httpd.conf
RewriteLock /var/lock/rewrite.lock
RewriteOptions`RewriteOptions` directive enables specific options for `mod_rewrite`.
RewriteOptions InheritDown
This makes the current configuration inherit rewrite rules from the parent scope (like the server config to virtual hosts, or from parent directories to subdirectories).
Security FeaturesHTTP Referrer-based RulesPrevent certain referrers from accessing your site's resources:
RewriteCond %{HTTP_REFERER} badsite\.com [NC]
RewriteRule .* - [F]
Password Protecting A DirectoryWhile you can use the `<Files>` directive to protect specific files, you can protect whole directories using `.htaccess` in combination with `.htpasswd`.
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
The `.htpasswd` file stores username and hashed password pairs.
Mod_SecurityIf you have the mod_security module enabled, `.htaccess` can be used to tweak its settings or disable it for certain scenarios.
<IfModule mod_security.c>
SecFilterScanPOST Off
</IfModule>
Performance OptimizationSetOutputFilterYou can use `SetOutputFilter` to filter the response from the server, which can be used for compression, transformation, etc.
SetOutputFilter DEFLATE
DirectoryIndexSpecifies which file to load as an index when a directory URL is accessed.
DirectoryIndex home.html index.cgi index.pl
If `home.html` is not found, it will look for `index.cgi`, and so on.
OptionsUsing the `Options` directive, you can enable or disable certain features within the directory where `.htaccess` is placed.
Options -Indexes
This would disable directory listing.
Server Variable ManipulationSetEnv and UnsetEnvSet or unset environment variables for use in your scripts or in the server configuration.
SetEnv MY_VARIABLE "value"
UnsetEnv MY_VARIABLE
Custom Error PagesDefine the path to custom error dоcuments using `Errordоcument`.
Errordоcument 404 /errors/notfound.html
Remember that `.htaccess` directives can have intricate interactions and can be affected by context and server configurations. Use these features responsibly, testing them in a controlled environment before deploying to a production setting, and always, as previously mentioned, have backups and a way to revert changes if something goes wrong.