Complete Guide to htaccess on Apache

htaccess & Redirects | Updated 2026

The .htaccess file is one of the most powerful tools available on your hosting account. It controls how Apache handles requests for your website, from simple redirects to complex security rules. This guide covers the most common uses with copy-and-paste examples that work on Ultra Web Hosting's servers. If you've never worked with .htaccess before, start with the basics section and work your way down.

02. How to Edit Your .htaccess File

There are two easy ways to edit your .htaccess file on Ultra Web Hosting:

Using cPanel File Manager

  1. Log into cPanel and click File Manager
  2. Navigate to the public_html folder
  3. Click Settings in the upper right and check Show Hidden Files, then save
  4. Click on the .htaccess file, then click Edit
  5. Make your changes and click Save Changes

If the file doesn't exist, click the +File button, name it .htaccess (including the dot), and create it in the public_html directory.

Using FTP

Connect with any FTP client (FileZilla, Cyberduck, WinSCP) and navigate to public_html. Enable "show hidden files" in your FTP client's settings to see the .htaccess file. Download, edit in a text editor (not Word), and re-upload.

Important

Always use a plain text editor (Notepad++, VS Code, nano, vim). Never use Microsoft Word or Google Docs, as they add invisible formatting characters that will break the file.

03. 301 Permanent Redirects

A 301 redirect tells search engines and browsers that a page has permanently moved to a new URL. Search engines will transfer the old page's ranking to the new URL. Use this when a page has been permanently renamed or relocated.

Redirect a single page

Redirect 301 /old-page.html https://www.yourdomain.com/new-page.html

Redirect an entire site to a new domain

Redirect 301 / https://www.newdomain.com/

Redirect using RewriteRule (more flexible)

RewriteEngine On
RewriteRule ^old-directory/(.*)$ https://www.yourdomain.com/new-directory/$1 [R=301,L]
SEO Note

301 redirects are the correct way to handle permanent URL changes. Google has confirmed that 301 redirects pass full link equity to the new URL.

04. 302 Temporary Redirects

A 302 redirect tells search engines the move is temporary and they should keep the original URL in their index. Use this for maintenance pages, A/B testing, or seasonal content.

Redirect 302 /sale.html https://www.yourdomain.com/holiday-sale.html

Redirect entire site temporarily

Redirect 302 / https://www.temporary-site.com/

05. Redirect Non-WWW to WWW (and Vice Versa)

Pick one version of your domain (www or non-www) and redirect the other to it. This prevents duplicate content issues in search engines.

Non-www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Www to non-www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

06. Force HTTPS

All Ultra Web Hosting accounts include free AutoSSL certificates. Use this rule to redirect all HTTP traffic to HTTPS:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Combined: Force HTTPS and WWW together

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]

07. Custom Error Pages

Replace Apache's default error pages with your own branded pages:

ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html

Create the HTML files in an /errors/ directory in your public_html. A good 404 page should include your site navigation, a search box, and links to your most popular content.

410 Gone (for permanently removed pages)

If a page no longer exists and has no replacement, a 410 tells search engines to stop trying to index it. This is better than letting them hit a 404 repeatedly:

Redirect 410 /removed-page.html

08. Directory Index and Default Pages

Control which file Apache serves when someone visits a directory without specifying a filename:

DirectoryIndex index.html index.php index.htm

Apache tries each file in order. If none exist, it either shows a directory listing or a 403 error (depending on the Options setting).

To disable directory browsing (recommended for security):

Options -Indexes

Stop other websites from embedding your images directly, which consumes your bandwidth:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp|svg)$ - [F,NC]

You can also use the Hotlink Protection icon in cPanel, which provides a GUI for this.

10. Block or Allow by IP Address

Block specific IPs

# Apache 2.4 (used on Ultra Web Hosting)
<RequireAll>
  Require all granted
  Require not ip 192.168.1.100
  Require not ip 10.0.0.0/8
</RequireAll>

Allow only specific IPs (lock down a directory)

<RequireAll>
  Require ip 203.0.113.50
  Require ip 198.51.100.0/24
</RequireAll>
Note

If your site uses Cloudflare, visitor IPs are replaced with Cloudflare's IPs. IP-based blocking in .htaccess won't work as expected. Use Cloudflare's firewall rules instead, or configure mod_remoteip to restore real visitor IPs.

11. Password-Protect a Directory

Add HTTP Basic Authentication to any directory. First, create a .htpasswd file (the easiest way is through cPanel's Directory Privacy tool). Then add to your .htaccess:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/username/.htpasswd
Require valid-user

Replace /home/username/ with your actual home directory path, which you can find in cPanel under "Server Information." Place the .htpasswd file outside of public_html so it can't be downloaded directly.

12. PHP Settings via .htaccess

You can override certain PHP settings per-directory using .htaccess. This is useful when a specific script needs different limits than the server default:

# Increase upload size limit
php_value upload_max_filesize 64M
php_value post_max_size 64M

# Increase memory limit
php_value memory_limit 256M

# Increase max execution time (in seconds)
php_value max_execution_time 300

# Increase max input variables (for complex forms)
php_value max_input_vars 5000

# Turn off error display on production
php_flag display_errors Off
CloudLinux Note

On Ultra Web Hosting, the server-wide PHP memory limit is 384MB. You can set values up to this limit via .htaccess. For PHP version changes, use the Select PHP Version tool in cPanel instead of .htaccess directives.

13. Browser Caching and Compression

Tell browsers to cache static files so repeat visitors load your site faster:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/webp "access 1 year"
ExpiresByType image/svg+xml "access 1 year"
ExpiresByType application/javascript "access 1 month"
ExpiresByType font/woff2 "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz|html|woff|woff2|ttf|svg)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

For a complete performance guide, see our article: Optimize WordPress Performance & Speed.

14. Security Hardening Rules

These rules protect sensitive files and block common attack patterns. Our full WordPress-specific security rules are in the WordPress Security guide, but these apply to any site:

# Block access to hidden files (.git, .env, .htpasswd)
RewriteRule ^\. - [F,L]

# Block access to log files and config backups
<FilesMatch "\.(log|sql|bak|old|orig|save)$">
  Require all denied
</FilesMatch>

# Disable directory browsing
Options -Indexes

# Prevent clickjacking
Header always set X-Frame-Options "SAMEORIGIN"

# Prevent MIME-type sniffing
Header always set X-Content-Type-Options "nosniff"

# Enable XSS protection
Header always set X-XSS-Protection "1; mode=block"

15. Exclude a Directory from Rules

Sometimes you need a subdirectory to be exempt from your main rewrite rules. Add this before the rules you want to skip:

# Exclude /api/ directory from all rewrites
RewriteEngine On
RewriteRule ^api/ - [L]

Exclude multiple directories

RewriteCond %{REQUEST_URI} !^/api/ [NC]
RewriteCond %{REQUEST_URI} !^/staging/ [NC]
RewriteCond %{REQUEST_URI} !^/dev/ [NC]
# ... your other rewrite rules follow

Allow Let's Encrypt validation (important for SSL renewals)

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/\.well-known/ [NC]
RewriteRule .* - [L]
When Things Break

16. Troubleshooting Common Problems

The most common .htaccess issues and how to fix them:

  • 500 Internal Server Error - Almost always a syntax error. Check for typos, missing closing tags, or directives your server doesn't support. Restore your backup to get the site back up, then fix the rule.
  • Redirect loops - Your rules are redirecting in a circle. Check for conflicting rules, especially if you have both www and HTTPS redirects. Combine them into a single rule block.
  • Rules not working - Make sure RewriteEngine On appears before your rewrite rules. Also check that you only have it listed once per .htaccess file.
  • File not found - The .htaccess file must be named exactly .htaccess (lowercase, with the leading dot). Some FTP clients hide it by default.
  • Changes not visible - Clear your browser cache (Ctrl+Shift+R) or test in an incognito window. If you're using Cloudflare, purge their cache too.

Need Help With .htaccess?

If you're not sure about a rule or something isn't working as expected, our support team is happy to help. We've been doing this since 2002.

Open a Support Ticket

Quick Recap: The Most Common Tasks

Here are the five things most people need .htaccess for:

  1. Force HTTPS - redirect all HTTP traffic to HTTPS with a 301 redirect
  2. Redirect old URLs - use 301 redirects to preserve SEO when pages move
  3. Standardize www/non-www - pick one and redirect the other
  4. Set custom error pages - replace Apache's ugly defaults with branded pages
  5. Disable directory browsing - add Options -Indexes for basic security

Last updated March 2026 · Browse all htaccess articles

  • 0 Users Found This Useful

Was this answer helpful?

Related Articles

htaccess referral redirect

Setting Up a Referral Redirect With .htaccess   A referral redirect (also called a...

Show longer file names in directory/folder index

If you've ever wanted to show longer file names in your directory listing just create or edit an...

Redirecting non-www to www with htaccess

Redirecting non-www to www with .htaccessIf you ever point your www. record to another server...

When I upload an htaccess file it disappears

Why Your .htaccess File Appears to Disappear After Uploading   On Linux servers, any file...

Disable error_log via htaccess

Disabling error_log Files via .htaccess   If your error_log file is growing large and...



Save 30% on web hosting - Use coupon code Hosting30