The post explains what an .htaccess file does in Apache and how to find, back up, and edit it safely in cPanel. It emphasizes testing changes immediately because small mistakes can cause 500 errors, break redirects, or affect WordPress and site access.
It also gives examples for redirects, HTTPS, domain canonicalization, caching, compression, security headers, access control, WordPress protections, and custom error pages. The post warns against outdated or risky rules and recommends using only small, well-tested directives.
.htaccess Information, Tricks, and Tips
The .htaccess file is a small configuration file that can control important parts of an Apache-powered website. It can create redirects, improve URLs, restrict access, block hotlinking, set browser caching, add security headers, and change how certain server errors are handled.
It is also very easy to break a website with one incorrect character.
Before editing an .htaccess file, download a backup copy. After saving a change, immediately test the website, WordPress administration area, important forms, and several internal pages. If the website begins displaying a 500 Internal Server Error, restore the previous file or remove the rule you just added.
What Is an .htaccess File?
An .htaccess file contains Apache configuration directives that apply to the directory where the file is located and, in most cases, the directories below it.
For example, an .htaccess file inside your main public_html directory normally affects the entire website. A second file placed inside public_html/downloads can contain additional rules that apply only to the downloads directory.
Apache reads these files during website requests, which means changes normally take effect immediately without restarting the web server.
The available rules depend on the server configuration and which Apache modules are enabled. Some hosting platforms also use Apache-compatible web servers such as LiteSpeed, which supports many common .htaccess directives.
How to Find .htaccess in cPanel
Files beginning with a period are treated as hidden files. If you cannot see .htaccess in cPanel:
- Open File Manager.
- Click Settings in the upper-right corner.
- Enable Show Hidden Files (dotfiles).
- Click Save.
- Open the document root for the website, which is commonly
public_html.
If the file does not exist, you can create a new plain-text file named exactly:
.htaccessDo not name it .htaccess.txt. Use a plain-text editor or the editor built into cPanel File Manager rather than Microsoft Word or another word processor.
Important Rules Before Editing
- Download a backup of the existing file first.
- Change one section at a time.
- Test the website immediately after every change.
- Keep comments above custom rules so you remember their purpose.
- Do not paste random security code from an old forum post.
- Do not place rules inside a WordPress-generated section unless the instructions specifically require it.
- Use permanent redirects only when the move is truly permanent.
You can add comments to an .htaccess file by starting the line with a number sign:
# Redirect the old contact page
Redirect 301 /contact-us/ /contact/1. Redirect an Old Page to a New Page
A 301 redirect tells browsers and search engines that a page has permanently moved.
Redirect 301 /old-page/ https://example.com/new-page/Replace example.com with your own domain.
Use a redirect when:
- A page URL has changed.
- Two pages have been combined.
- A product or service has moved to a new section.
- An old domain has been replaced by a new domain.
Do not redirect every deleted page to the homepage. Redirect it to the closest relevant replacement. If there is no useful replacement, allowing the old URL to return a proper 404 or 410 response may be more accurate.
2. Redirect an Entire Domain
To permanently move an entire website to a new domain while preserving the requested path:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?old-domain\.com$ [NC]
RewriteRule ^ https://new-domain.com%{REQUEST_URI} [R=301,L]A request for:
https://old-domain.com/services/hosting/would be redirected to:
https://new-domain.com/services/hosting/Preserving the path is better for visitors and SEO than sending every old URL to the new homepage.
3. Force HTTPS
If an SSL certificate is installed but visitors can still access the unsecured HTTP version, you can redirect them to HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Some hosting platforms, CDNs, reverse proxies, and load balancers handle HTTPS differently. If this rule creates a redirect loop, remove it and use the HTTPS or redirect option provided by your host or CDN instead.
Web Host Pro includes free SSL certificates with supported hosting plans and provides LiteSpeed-powered hosting with cPanel access.
4. Choose WWW or Non-WWW
Your website should normally use one consistent version of its domain. You can use either www.example.com or example.com, but avoid leaving both versions available without redirection.
Redirect WWW to the Non-WWW Version
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]Redirect Non-WWW to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]Only use one of these examples. Replace every occurrence of example.com with your real domain.

5. Redirect a Folder
To move an old website section to a new location:
Redirect 301 /old-section/ https://example.com/new-section/For more complicated folder migrations where every remaining part of the path must be preserved, use mod_rewrite:
RewriteEngine On
RewriteRule ^old-section/(.*)$ /new-section/$1 [R=301,L]This would redirect:
/old-section/example-page/to:
/new-section/example-page/6. Create a Custom 404 Page
A custom 404 page can help visitors recover when a URL does not exist.
ErrorDocument 404 /404.htmlThe custom page should still return a real 404 status. Do not simply redirect every missing URL to the homepage, because that can confuse visitors, search engines, and website reporting tools.
A useful 404 page can include:
- A simple explanation that the page could not be found
- A link to the homepage
- A website search box
- Links to important services or categories
- A way to report a broken link
7. Prevent Directory Browsing
If a directory does not contain an index file, some servers may display a list of its files. You can disable directory listings with:
Options -IndexesThis does not protect files that someone already knows how to access. It only prevents the server from automatically displaying a browsable directory listing.
8. Protect Sensitive Files
The following rule blocks web access to the .htaccess and .htpasswd files:
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>You can also block access to common backup, log, and configuration file extensions:
<FilesMatch "\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)$">
Require all denied
</FilesMatch>Do not rely on this rule as your only protection. Sensitive files and backups should ideally be stored outside the public website directory.
9. Password-Protect a Directory
Apache Basic Authentication can protect a staging area, private download directory, or internal tool.
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/account/.htpasswds/private/passwd
Require valid-userThe AuthUserFile path must be the complete server path to a valid password file. Do not place the password file inside a publicly accessible directory.
cPanel users can usually configure this more safely through the Directory Privacy feature rather than manually creating password files.
Basic Authentication should be used over HTTPS because the login information is not protected by the authentication method alone.
10. Allow or Block a Specific IP Address
Apache 2.4 uses the Require directive for access control.
Block One IP Address
<RequireAll>
Require all granted
Require not ip 192.0.2.25
</RequireAll>Allow Only One IP Address
Require ip 192.0.2.25Replace the example IP address with the correct address. Be careful when restricting access because many internet connections use addresses that change over time.
Blocking a few abusive IP addresses can be useful, but an .htaccess file is not a replacement for a firewall, malware scanner, login protection, or server-level security system.

11. Stop Image Hotlinking
Hotlinking happens when another website embeds an image directly from your server. Their page displays your image while your hosting account supplies the file and bandwidth.
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/ [NC]
RewriteRule \.(gif|jpe?g|png|webp|svg)$ - [F,L,NC]Replace example.com with your domain.
The first condition allows requests with no referrer because legitimate browsers, privacy tools, email clients, search tools, and other applications may omit that information.
Hotlink protection can also interfere with:
- CDN delivery
- Social media previews
- Image search results
- Email newsletters
- Authorized partner websites
- External apps that display your images
Test carefully and add approved domains as additional allowed referrers when needed.
12. Add Browser Caching
Browser caching allows returning visitors to reuse certain static files instead of downloading them again during every visit.
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType text/html "access plus 1 hour"
</IfModule>Long expiration periods work best when filenames change whenever the file changes, such as:
website-style-v3.cssIf you use WordPress caching, LiteSpeed Cache, a CDN, or another optimization system, it may already add caching rules. Do not create duplicate or conflicting sections without checking the existing configuration.
13. Enable Compression
Text files such as HTML, CSS, JavaScript, XML, and JSON can often be compressed before being sent to the browser.
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>Modern hosts and CDNs may already provide Gzip or Brotli compression. Adding another compression layer will not necessarily make the website faster and can create confusing results.
14. Add Basic Security Headers
Apache’s mod_headers module can modify HTTP response headers.
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set X-Frame-Options "SAMEORIGIN"
</IfModule>These rules can provide useful baseline protection, but they are not universal. For example, X-Frame-Options SAMEORIGIN may interfere with a page that intentionally needs to appear inside an iframe on another domain.
A Content Security Policy can provide stronger control over scripts, frames, images, fonts, and other resources, but it should not be copied blindly. An incorrect policy can break analytics, payment systems, forms, embedded videos, fonts, and WordPress plugins.
15. Remove an Unwanted Query String During a Redirect
Sometimes an old URL includes a query string that should not be carried to the new page.
RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=123$
RewriteRule ^old-page\.php$ /new-page/? [R=301,L]For newer Apache versions, the QSD flag provides a clearer way to discard the query string:
RewriteEngine On
RewriteRule ^old-page\.php$ /new-page/ [R=301,L,QSD]16. Redirect Only a Specific Query String
This example redirects an old dynamic URL to a cleaner permanent URL:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^product=hosting$
RewriteRule ^product\.php$ /web-hosting/ [R=301,L,QSD]It changes:
/product.php?product=hostingto:
/web-hosting/17. Block Access to WordPress XML-RPC
WordPress includes an xmlrpc.php endpoint that may be used by remote publishing tools, mobile applications, Jetpack, and other services.
If you are certain that your website does not use XML-RPC, you can block direct access:
<Files "xmlrpc.php">
Require all denied
</Files>Do not add this rule merely because another article calls XML-RPC dangerous. It may disable legitimate services connected to the website.
18. Protect WordPress wp-config.php
The WordPress wp-config.php file contains important configuration information.
<Files "wp-config.php">
Require all denied
</Files>Apache and properly configured hosting environments should not normally serve PHP source code directly, but explicitly denying web access adds another layer of protection.
19. Prevent Direct Access to Backup Archives
Website owners sometimes leave ZIP, TAR, SQL, and backup files inside public_html. That is dangerous because anyone who discovers the filename may be able to download the entire backup.
<FilesMatch "\.(zip|tar|tar\.gz|tgz|gz|7z|sql)$">
Require all denied
</FilesMatch>The better solution is to move backups outside the public website directory or store them in a dedicated remote backup system.
20. Set a Default Index File
You can control which file Apache loads when someone visits a directory without specifying a filename:
DirectoryIndex index.php index.htmlApache will check the files in the listed order. In this example, it will load index.php first and use index.html if the PHP file does not exist.
Understanding Common Rewrite Flags
Rewrite flags appear inside square brackets at the end of a RewriteRule.
R=301creates a permanent external redirect.R=302creates a temporary external redirect.Ltells Apache to stop processing the current rewrite rules after that rule matches.NCmakes the match case-insensitive.Freturns a 403 Forbidden response.QSAappends the original query string to the new one.QSDdiscards the original query string.
The order of rewrite rules matters. Apache evaluates them from top to bottom, and one broad rule can prevent a later, more specific rule from ever running.
Rules You Should Avoid
Massive User-Agent Blocklists
Old .htaccess guides often contain hundreds of lines that block download programs, crawlers, or bots by name.
This is weak protection because a user-agent string is supplied by the visitor and can be changed easily. Large lists also create maintenance problems and can accidentally block legitimate search engines, accessibility tools, uptime monitors, or customers.
Referrer-Based Login Protection
Do not use the HTTP referrer as proof that someone is authorized to view a private page. Referrer information may be missing, changed, or spoofed. Real authentication should be handled through server authentication, application sessions, signed tokens, or another proper access-control system.
Redirecting Attackers to Another Website
Old tutorials sometimes recommend redirecting unwanted traffic to another website. That does not secure your website and may create unnecessary legal, ethical, and technical problems. Return a 403 response or block the request at the firewall instead.
Copying a Complete “Ultimate Security” File
A large generic security file may block WordPress REST requests, payment callbacks, search-engine crawlers, image delivery, API connections, or legitimate uploads. Add only rules that solve a problem you understand.
WordPress .htaccess Rules
A standard WordPress installation commonly includes a generated section similar to this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPressWordPress or a plugin may rewrite anything between the BEGIN WordPress and END WordPress comments. Place your own redirects and custom rules outside that generated block unless a plugin specifically instructs otherwise.
When possible, place simple redirects before the main WordPress rewrite section so they are handled before WordPress routes the request through index.php.
How .htaccess Can Affect SEO
An .htaccess file does not improve search rankings by itself, but incorrect rules can seriously damage SEO.
Common SEO problems caused by bad rules include:
- Redirect loops
- Redirect chains
- HTTP and HTTPS versions remaining available
- WWW and non-WWW versions remaining available
- Every missing page redirecting to the homepage
- Important pages returning 403 errors
- Search-engine crawlers being blocked
- Old URLs redirecting to irrelevant pages
- Query strings being removed accidentally
- Internal rewrites being mistaken for external redirects
After making major URL changes, test the old and new URLs and review the website in Google Search Console. You can also use website analysis tools from PageRanked to identify redirects, broken pages, and other website issues.
Troubleshooting a Broken .htaccess File
If your website stops working after editing .htaccess:
- Rename the file temporarily to something such as
.htaccess-disabled. - Reload the website.
- If the website works again, the problem is inside that file.
- Restore your backup copy.
- Add the new rules again one section at a time.
- Check the hosting error log for the exact Apache error.
Common causes of 500 errors include:
- A misspelled directive
- An unsupported Apache module
- Apache 2.2 syntax on an Apache 2.4 server
- Missing closing tags such as
</FilesMatch> - Copied smart quotation marks instead of normal quotation marks
- Using a directive that the hosting provider does not allow
- A malformed regular expression
When Not to Use .htaccess
If you manage your own VPS or dedicated server, important server-wide rules are usually better placed in the Apache virtual host or main server configuration.
Apache checks for .htaccess files during requests. Main server configuration can be more efficient and easier to control when you have administrative access.
However, most shared hosting customers do not have access to the main server configuration. For those users, .htaccess remains a practical way to manage website-level redirects and settings.
Final Advice
The best .htaccess file is not the longest one. It is the smallest file that performs the required jobs clearly and correctly.
Use it for specific redirects, access rules, caching settings, and carefully tested server behavior. Avoid giant collections of tricks copied from old websites. Many of those rules are obsolete, ineffective, or more likely to block legitimate traffic than stop a real attack.
For managed help with Apache-compatible hosting, WordPress, SSL, redirects, security, and cPanel, visit Web Host Pro. Web Host Pro has provided professional website hosting and real-person support since 2001.
Website owners can also list their businesses on BizFaves, connect with marketing professionals through Marketing Spot, and use website improvement resources from PageRanked.

