'.htaccess' is Apache's folder-level configuration file. Placed in the site root, it changes many settings without restarting the server: redirects, security, caching, pretty URLs. Nginx doesn't have it (config is admin-only), but on shared hosting Apache dominates.
Force redirect to HTTPS
The very first rule. Sends all HTTP requests to HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Remove www (or add it)
Redirect to the non-www version (prevents duplicates):
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
301 redirect (old page โ new)
Preserve old addresses when the site is updated:
Redirect 301 /old-page.html https://sayt.uz/new-page
Very important for SEO โ passes the old page's authority to the new one.
Pretty URLs (hide .php)
Show /blog instead of blog.php:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]
Custom error pages
ErrorDocument 404 /404.php
ErrorDocument 403 /403.php
File protection
Deny access to secret files:
<Files ".env">
Require all denied
</Files>
Gzip compression (speed)
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
Browser cache
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/webp "access plus 1 month"
</IfModule>
Hotlink protection
Stops other sites from using your images on their pages and eating your bandwidth.
Be careful
1) A syntax error takes down the whole site (500 error). Back up first. 2) Test the site after each rule. 3) RewriteRule order matters.
Sayt.uz practice
Sayt.uz's '.htaccess' has HTTPS forced, .php hiding, a 404 page, gzip and caching. Secret files are protected.