Most websites run on Apache servers rely on the same core functionality, but what separates high-performing sites from average ones? Often, it’s mastery of the humble .htaccess file.
In this guide, we outline the Apache .htaccess file and the powerful commands you can use to customize your website’s behavior. Whether you need to implement redirects, enhance security, optimize performance, or configure WordPress settings, these essential .htaccess commands will give you greater control over your web server.
Key Points
- 301 and 302 redirects control user navigation and preserve SEO value when moving content or changing domains.
- Security commands can block malicious bots, prevent hotlinking, and protect sensitive WordPress files from unauthorized access.
- Performance optimization through GZIP compression and browser caching can dramatically improve page load speeds and Core Web Vitals scores.
- WordPress sites benefit from specific .htaccess configurations that enhance security and enable SEO-friendly permalink structures.
- A single syntax error in your .htaccess file can take down your entire website—always back up before making changes.
What are .htaccess commands?
.htaccess commands are powerful directives that give you granular control over your Apache web server without requiring root access or server restarts. Unlike most configuration options, these commands take effect immediately and can transform how your website functions.
What makes .htaccess commands indispensable:
- They operate at the directory level, allowing precise control over specific site sections.
- Changes take effect instantly without server restarts.
- They enable critical functionality like URL rewrites, security hardening, and performance tuning.
- They’re accessible even on shared hosting environments where server configuration is restricted.
In short, .htaccess commands are your direct line to server behavior modification – without needing a systems administrator.
Accessing your .htaccess file
The .htaccess file is hidden by default (note the leading dot) in your website’s root directory. You can access it through:
- SSH: Direct command-line editing with nano, vim, or your preferred editor
- FTP/SFTP: Upload a pre-configured file from your local machine
- Control Panel: Most hosting providers offer built-in file managers (enable “Show Hidden Files” to see it)
Warning: Always backup your existing .htaccess file before making changes. A single syntax error can take down your entire website.
Let’s dive into the commands that will transform how your website functions.
URL redirects and rewrites
URL redirects and rewrites are among the most common uses for .htaccess commands. They allow you to control how visitors navigate your site and how URLs are displayed.
Simple redirect commands
Redirect an individual page
To send visitors from an old page to a new one, use the 301 (permanent) redirect command:
Redirect 301 /old.html https://www.example.com/new.html
For a temporary redirect, change 301 to 302:
Redirect 302 /temporary.html https://www.example.com/new-temp.html
Redirect an entire website
When changing domain names while keeping the old one active, use this command to redirect all traffic:
Redirect 301 / https://www.newdomain.com/
This preserves the URL path structure, so oldsite.com/about will redirect to newdomain.com/about.
Rewrite commands
Rewrite commands (using mod_rewrite) offer more flexibility than simple redirects. They’re especially useful for complex URL manipulations.
Rewrite a site address from WWW to Non-WWW
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^example\.com
RewriteRule (.*) http://example.com/$1 [R=301,L]Rewrite a site address from Non-WWW to WWW
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]Rewrite a site address without changing the URL
This command redirects requests to an external domain while maintaining the original URL in the browser’s address bar:
RewriteCond %{REQUEST_URI} ^/specific-url/
RewriteRule ^(.*)$ https://external-domain.com/specific-url/ [P]Rewrite a page without changing the URL
Useful when you’ve renamed or moved a page but want to maintain the original URL in the browser:
RewriteEngine on
RewriteRule "^/old-page\.html$" "/new-page.html" [PT]Rewrite to force HTTPS connections
Ensure all connections use the secure HTTPS protocol:
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]Rewrite file names without the extension
Remove file extensions from URLs for a cleaner appearance:
RewriteEngine on
RewriteRule ^/?(.*).(php|html|htm)$ /$1 [R=301,L]Rewrite a subdomain to a directory
Redirect subdomain requests to a specific directory:
RewriteEngine on
RewriteRule ^(.*)$ https://example.com/directory/$1 [L,NE,R=301]Security commands
Properly configured .htaccess commands can significantly enhance your website’s security. Here are essential security measures you can implement:
Blocking malicious bots and scrapers
Block access from specified user agents (bots):
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^BadBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^ScraperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^MaliciousBot
RewriteRule ^.* - [F,L]Blocking IP addresses
Block access from specific IP addresses:
# Apache 2.4+
Require all granted
Require not ip 123.456.789.123
Require not ip 987.654.321.987Implementing HTTP Strict Transport Security (HSTS)
Force browsers to use HTTPS for enhanced security:
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</IfModule>Advanced hotlinking protection
Prevent other websites from embedding your images and consuming your bandwidth:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com/.*$ [NC]
RewriteRule \.(gif|jpg|jpeg|png)$ https://www.example.com/hotlink-denied.png [R,L]Protecting sensitive files and directories
Prevent access to hidden files and directories:
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Deny access to backup and source files:
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
# Apache 2.4+
Require all denied
</FilesMatch>Password-protected content
Secure specific directories with password protection:
AuthType Basic
AuthName "Protected Area"
AuthUserFile "/home/user/.htpasswds/passwd"
Require valid-userYou’ll need to create a password file using the htpasswd command:
htpasswd -c /home/user/.htpasswds/passwd usernameRate limiting and brute force protection
Limit requests to prevent brute force attacks (requires mod_ratelimit):
<IfModule mod_ratelimit.c>
# Limit requests to login pages
<LocationMatch "wp-login.php">
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 5
</LocationMatch>
</IfModule>Performance optimization commands
Optimize your website’s performance with the following .htaccess commands:
Enabling GZIP compression
Compress text-based files to reduce transfer size and improve load times:
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
</IfModule>Browser caching implementation
Set appropriate cache headers to reduce server load and improve page speed:
<IfModule mod_expires.c>
ExpiresActive On
# Images
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
# Video
ExpiresByType video/mp4 "access plus 1 year"
ExpiresByType video/mpeg "access plus 1 year"
# CSS, JavaScript
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
# Others
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
</IfModule>Optimizing resource loading
Remove ETag headers to improve caching:
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NonePerformance considerations
While .htaccess files provide flexibility, they can impact performance if overused. Each time a page is requested, Apache must look for and process .htaccess files in the current directory and all parent directories.
For optimal performance:
- Minimize the number of .htaccess files
- Keep them as small as possible
- Use server-level configurations when you have server access
- Combine similar rules to reduce redundancy
WordPress-specific commands
WordPress sites often benefit from special .htaccess configurations:
WordPress permalinks configuration
Enable pretty permalinks in WordPress:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPressProtecting wp-login.php
Prevent brute force attacks on your login page:
# Limit access to wp-login.php
<Files wp-login.php>
# Allow only specific IP addresses
Order Deny,Allow
Deny from all
Allow from 123.456.789.123
# Alternatively, use environment variables
# SetEnvIf X-Forwarded-For "123\.456\.789\.123" allow_access
# Order Deny,Allow
# Deny from all
# Allow from env=allow_access
</Files>Multisite configuration
Enable WordPress Multisite with subdirectories:
# BEGIN WordPress Multisite
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# Add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress MultisiteWP Content security enhancements
Protect sensitive WordPress files:
# Protect wp-config.php
<Files wp-config.php>
Order Allow,Deny
Deny from all
</Files>
# Protect .htaccess and .htpasswd
<Files ~ "^\.ht">
Order Allow,Deny
Deny from all
</Files>
# Disable PHP execution in uploads directory
<Directory /wp-content/uploads/>
<Files *.php>
Order Deny,Allow
Deny from all
</Files>
</Directory>Additional setups
Custom error pages
Create personalized error pages for a better user experience:
ErrorDocument 401 /custom-error-pages/unauthorized.html
ErrorDocument 403 /custom-error-pages/forbidden.html
ErrorDocument 404 /custom-error-pages/not-found.html
ErrorDocument 500 /custom-error-pages/server-error.htmlLink protection
Prevent hotlinking by restricting access to your resources:
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com/ [NC]
RewriteRule \.(gif|jpg|png)$ /images/hotlink-denied.png [NC,R,L]Common .htaccess troubleshooting
Syntax error diagnosis
If your site shows a “500 Internal Server Error” after modifying .htaccess:
1. Check your syntax with this test command if you have SSH access:
apachectl -t2. Revert to your backup immediately
3. Look for missing brackets, incorrect spacing, or syntax errors
Testing command functionality
Test new commands in a subdirectory before implementing them site-wide. This limits potential disruption if something goes wrong.
Server configuration compatibility
Not all Apache installations support all .htaccess directives. If a command isn’t working:
- Check if the required Apache module is enabled
- Verify your hosting provider allows the specific commands
- Look for alternatives that might work with your server configuration
Conclusion: Mastering .htaccess commands
The .htaccess file is a powerful tool for customizing your Apache web server’s behavior. From redirects and URL rewrites to security enhancements and performance optimization, these commands give you granular control without requiring server-level access.
Remember to always back up your .htaccess file before making changes, and test modifications carefully to ensure they’re working as expected. While .htaccess commands offer flexibility and convenience, they should be used judiciously to maintain optimal server performance.
By mastering these essential .htaccess commands, you’ll be well-equipped to enhance your website’s functionality, security, and user experience.
We Can Help!
We pride ourselves on being The Most Helpful Humans In Hosting™!
Our Support Teams are filled with experienced Linux technicians and talented system administrators who have intimate knowledge of multiple web hosting technologies, especially WordPress hosting.
If you are a Fully Managed VPS server, VMware Private Cloud, Cloud Dedicated, Private Parent server, Managed Cloud Servers, or a dedicated server owner and you need additional or more specific information about your .htaccess file, setting up redirects, or any other concerns, you can reach out to our award-winning support via a LiveChat. Our technical support staff is always available to answer questions if you need additional information about this article, 24 hours a day, 7 days a week, 365 days a year. Support is also available via our ticketing systems by emailing us at [email protected].
Misael Ramirez