In this article · 9 sections
On Apache and LiteSpeed hosting (including Hostinger), the .htaccess file lets you control redirects, URL rewriting, security and caching per folder, without server access. A single typo can break the whole site, so always keep a backup copy before editing.
Force HTTPS and remove www
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
Pick one version (www or non-www) and redirect the other, so Google sees one site.
301 redirects for changed URLs
Redirect 301 /old-page.html /new-page
Redirect 301 /services.php /services
Use 301 (permanent) to keep SEO value when you rename pages or move from .html to PHP.
Clean URLs
Turn /taxi.php?route=ludhiana-to-delhi into /taxi/ludhiana-to-delhi:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^taxi/([a-z0-9-]+)/?$ taxi.php?route=$1 [L,QSA]
Hide .php extensions:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([a-z0-9-]+)/?$ $1.php [L]
QSA keeps extra query parameters (like ?utm_source=).
Custom 404 page
ErrorDocument 404 /404.php
Make sure 404.php sends a real 404 status: http_response_code(404);.
Security rules
Options -Indexes
<FilesMatch "\.(env|sql|log|bak|ini)$">
Require all denied
</FilesMatch>
<Files "config.php">
Require all denied
</Files>
Options -Indexes stops folder listings. The rules above block downloads of sensitive file types. (Require all denied is Apache 2.4 syntax.)
Browser caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
See browser caching with .htaccess.
Debugging
- 500 Internal Server Error right after editing usually means a syntax error or an unsupported directive; restore the backup and add rules one at a time
- Redirect loops: check that conditions prevent the rule from matching its own target; test in a private window (browsers cache 301s)
- Subfolders can have their own
.htaccess; rules there apply only to that folder. Root rules don't automatically apply inside a folder that has its ownRewriteEngine On
Nginx?
Nginx ignores .htaccess; equivalent rules go in the server config.
FAQs
Does .htaccess slow my site?
The effect is tiny for normal-sized files. Keep it tidy and avoid hundreds of individual redirects where a pattern works.
Where is the file?
In public_html. It starts with a dot, so enable "show hidden files" in File Manager.
Was this article helpful?
Your answer helps us improve our guides