What is the .htaccess file?
The .htaccess file is an Apache configuration file located in your public_html folder. It controls redirects, security, caching, and many other server rules. It is invisible by default — you must enable "Show Hidden Files" in cPanel's File Manager to view it.
Force HTTPS (redirect HTTP → HTTPS)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Redirect www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Redirect a specific URL to another
Redirect 301 /old-page https://yourdomain.com/new-page
Difference between 301 and 302
- 301 — Permanent: Tells Google the page has moved permanently. Transfers SEO value.
- 302 — Temporary: Temporary redirect. Google keeps the original URL in its index.
⚠️ Caution: A syntax error in .htaccess can cause a 500 Error across your entire site. Always save a backup before modifying it.