Hosting & Domaining Forum

Hosting Discussion => Web Hosting => Hosting FAQs => Topic started by: Sevad on Jan 02, 2024, 12:37 AM

Title: .htaccess File
Post by: Sevad on Jan 02, 2024, 12:37 AM
.htaccess File


(https://royalhost.net/blog/wp-content/uploads/2023/06/htaccess.webp)

Common Uses of .htaccess:



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 Addresses
You 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 Limits
For 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 Content
Hotlinking 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 URLs
Search 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 Zone
You can set the preferred time zone directly from .htaccess:

SetEnv TZ America/Los_Angeles

Custom File Types
Sometimes, 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 Encoding
You can manage character encodings to ensure text is displayed correctly:

AddDefaultCharset UTF-8

When writing rules and deploying changes through .htaccess:


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 Cases

Setting Custom PHP Values
If 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 Files
You 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 HTTPS
Redirect 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 Agents
Some 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 Compression
Improve 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-Control
Optimize 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 Includes
Prevent 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 ETags
Configure 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 Techniques

RewriteMap
If 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]

RewriteLock
When 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 Features

HTTP Referrer-based Rules
Prevent certain referrers from accessing your site's resources:

RewriteCond %{HTTP_REFERER} badsite\.com [NC]
RewriteRule .* - [F]

Password Protecting A Directory
While 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_Security
If 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 Optimization

SetOutputFilter
You can use `SetOutputFilter` to filter the response from the server, which can be used for compression, transformation, etc.

SetOutputFilter DEFLATE

DirectoryIndex
Specifies 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.

Options
Using 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 Manipulation

SetEnv and UnsetEnv
Set or unset environment variables for use in your scripts or in the server configuration.

SetEnv MY_VARIABLE "value"
UnsetEnv MY_VARIABLE

Custom Error Pages
Define 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.