Last Updated on April 29, 2024 by Sunny Staff
If you’ve been working with WordPress for some time you’ll have come across mention of the .htaccess file. It’s a configuration file used in Apache and Apache-based web servers that can be used to make directory-level configuration changes to your site’s behavior, performance, security, and much more.
One of the awesome benefits of learning how to use the .htaccess file effectively in WordPress is that it can put the power of advanced web server configurations at your fingertips, and greatly reduce the number of plugins required for a variety of tasks – from redirecting URLs to improving site speed, security, and overall performance.
In this article |
---|
Edit the .htaccess file using cPanel |
Seven .htaccess Tips for Clever Site Owners |
Don’t feel like doing all the tech heavy lifting? |
FAQ: WordPress .htaccess |
Edit the .htaccess file using cPanel
The .htaccess file is usually located in the root of your site’s directory on the server, often in the same directory where you’ll also find wp-config.php. (But, it can be placed in any directory on the web server, and will apply to the directory it is in and all of its subdirectories.)
The dot in front of .htaccess means it’s a hidden file, so if you can’t see it, remember to enable “View hidden files and folders”. Once you’ve located the .htaccess file, open it using a text editor, like Notepad.
Important: Back up all your WordPress website files and your database before you start working with your .htaccess file. It is also strongly recommended to work on a development or staging site before copying your .htaccess file to your live site.
If you have access to a web control panel like cPanel, you can edit the .htaccess in your browser. Follow these easy steps:
Once you’ve logged into your cPanel account, locate and open the File Manager.
Once the File Manager is open, navigate to your site’s document root. This is usually called public_html.
Look through the list in your public_html folder and locate your .htaccess file. Click on it once, and then click Edit in the top menu.
Click Edit on the Edit popup.
You can now edit your .htaccess file.
Remember to make regular backups of your .htaccess file as you work – one misplaced character can bring your entire site to a halt.
Also read: How To Fix the WordPress White Screen of Death Like a Pro
Seven .htaccess Tips for Clever Site Owners
There are many, many ways to use the .htaccess file to tweak the performance or security of your website. We’ve taken 7 of the best ones to get you started and show you how to use them below.
1. Preventing directory/folder browsing
If directory browsing is not disabled and there is no index.html or index.php, anyone can view the content of the directories where your site’s files are stored. This also means those files can be downloaded – that $100 plugin can now also be used by someone else. Here’s an example of such a directory:
WordPress’s .htaccess file can be used to prevent directory listings with a simple line of code:
Options -Indexes
This method relies on “security through obscurity”, which keeps knowledge of the actual paths and names of files a secret (by not displaying them) without actually hiding or restricting access to them.
2. Block IP addresses
WordPress’s .htaccess can also be used to block or allow IP addresses. For some, this might be preferable to using complicated firewall commands or installing an additional plugin to do the job.
order allow,deny
deny from 123.0.0.0
deny from 123.45.6.7
allow from all
The code above denies all traffic from IP addresses 123.0.0.0 and 123.45.6.7, and then allows traffic from all other IP addresses.
order allow,deny
allow from 123.0.0.0
allow from 123.45.6.7
deny from all
The inverse can also be used, with traffic allowed only from selected IP addresses, while traffic from all others is denied.
3. How to redirect URLs in WordPress with .htaccess
Of the many types of redirects, two are the most common:
301 Redirects: The 301 response code indicates that this is a permanent redirect. In other words, the browser is redirected to the new resource, and search engines update their links.
302 Redirects: The 302 response code indicates that this is a temporary redirect. Browsers are directed to a new resource, but search engines do not update their links.
You can implement a redirect in your .htaccess file with a simple line of code:
Redirect 301 /old-page/ https://www.yourdomain.com/new-page/
In the code above, 301 can be substituted with 302. While the ‘old’ or source URL can be relative to the domain (for example /old-page/ for https://www.yourdomain.com/old-page/), best practice prefers the destination URL to be absolute and include the full path, for example, https://www.yourdomain.com/new-page/.
Also read: Managing WordPress Slugs – Here’s How and When to Change Them
4. How to redirect folders in WordPress with .htaccess
Just like you can use .htaccess in WordPress to redirect individual pages as indicated above, you can also use it to redirect traffic from one folder to another. Again, we’ll use the Redirect directive to get the job done.
Redirect 301 /old-directory/ https://www.yourdomain.com/new-directory/
But what if we wanted a bit more flexibility with the redirection? While the Redirect directive is excellent for simple tasks, there’s a better and more versatile alternative that allows for more nuanced customization: RewriteRule
.
Using the Rewrite directive, we can achieve the same result with:
RewriteEngine on
RewriteRule "^old-directory/$""/new-directory/"[R,L]
Here we’re telling the webserver to send everything that matches old-directory
exactly to new-directory
. [R,L]
are flags, with R
specifying a redirection, and L
, or ‘Last’, specifying that no further rules should be processed for that specific rule (if there is a match).
Using the [R]
flag as it is used above will implement a 302 or temporary redirect, which means search engines won’t update their links to reflect the new URL. A permanent redirect should be instituted with [R=301,L]
.
To showcase the flexibility of the RewriteRule
directive, we can use an example scenario where we want to permanently redirect all traffic to categories ending in -’shoes’ to ‘footwear’.
RewriteRule ^category/(.+)-shoes/(.+)$ /category/footwear/$1/$2 [R=301,L]
Traffic intended for posts in any category ending with ‘-shoes’ will be redirected to a new category called ‘footwear’. For example, https://www.yourdomain.com/category/formal-shoes/leather will now redirect (permanently, because R=301
) to https://www.yourdomain.com/category/footwear/formal/leather.
In the statement above, the caret ^
and dollar sign $
respectively indicate the start and the end of the pattern to match. (.+)
means ‘anything’ and also captures that value to be (optionally) used later in the statement ($1
and $2
. There’s little correlation between $
and $n
.).
5. WordPress .htaccess: redirecting all website traffic to HTTPS
If you’re building a new site or updating an old site, chances are you’ll have to redirect traffic from unsecured HTTP to secure HTTPS at some point to keep your visitors and site safe and to give yourself a little search engine rank boost. The .htaccess file can be used to easily redirect HTTP to HTTPS.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Here’s what it means:
RewriteEngine On
, as the name suggests, activates the server’s RewriteEngine. But, for the rewrite rule to be applied to HTTP traffic only, we need to ensure that the HTTPS environment variable is off, hence RewriteCond %{HTTPS} off
. Finally, we can permanently rewrite all HTTP URLs to HTTPS.
6. How to enable caching with WordPress .htaccess
The .htaccess file can also be used to enable caching to speed up content delivery to your visitors and reduce the load on the server. It also reduces bandwidth usage when static resources and data are compressed. .htaccess can be used to achieve two caching at either server level, or using the visitor’s browser. The method below illustrates browser caching using the .htaccess file:
FileETag MTime Size
AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript
ExpiresActive On
ExpiresByType text/html "access 600 seconds"
ExpiresByType application/xhtml+xml "access 600 seconds"
ExpiresByType text/css "access 1 month"
ExpiresByType text/javascript "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresDefault "access 1 month"
Caching static resources and compressing data reduces overall bandwidth usage, which can be beneficial for both servers and clients, especially in bandwidth-constrained environments.
FileEtag MTime Size
The FileETag directive in Apache’s configuration lets you configure which properties of a file are used to generate the ETag (Entity Tag) header in HTTP responses. FileEtag is used to determine when a new copy of a file should be downloaded.
AddOutputFilterByType
uses the DEFLATE algorithm to compress specific types of content. This reduces the amount of data transmitted over the network and improves content load times.
ExpiresActive On
tells web browsers and other clients how long to cache the content before it should be requested again from the server. This directive is often accompanied by ExpiresByType which specifies the caching policies for different types of content.
If you’re running a server (or if you have the appropriate permissions on someone else’s server), the .htaccess file can also be used to enable server-side caching.
The following code enables cached content to be served from the server’s disk, which means it doesn’t have to be generated anew with each request. This reduces load on the server, and can dramatically speed up page load times.
CacheEnable disk /
CacheIgnoreNoLastMod On
CacheMaxExpire 86400
CacheHeader on
Here’s what it means:
CacheEnable disk /
enables disk-based caching. The forward slash “/” specifies the URL path for which caching is enabled – the whole website in this case. If you only wanted to enable caching for images served from the /image directory, the statement would read CacheEnable disk /images.
CacheIgnoreNoLastMod On
specifies that content without a last-modified date should also be cached (previously, content without a last-modified date was ignored).
CacheMaxExpire 86400
specifies the maximum amount of time (in seconds) content is considered ‘fresh’ before it should be re-cached.
CacheHeader On
includes additional information in the HTTP header that states whether the content was cached or not. Useful when you’re debugging code, etc.
More information about caching with .htaccess can be found on the Apache website’s mod_cache page.
7. Prevent hotlinking
Hotlinking refers to the practice of embedding media (files, images, and videos) without the permission of the content owner. Where other sites are hotlinking to your content, it can increase your server’s load and, as a result, decrease your website’s performance.
In the example below we’re using the .htaccess file to block other sites from hotlinking to images on a WordPress site with the following code:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
Use this code by replacing yourdomain.com with the name of your domain. The extensions in parentheses (jpg|jpeg|png|gif) are the file extensions that will be blocked. Add more extensions at your discretion (e.g. pdf), separating them with ‘|’.
Also read: Setting Up WordPress Multisite A Comprehensive Tutorial
FAQ: WordPress .htaccess
What is .htaccess and how does it work with WordPress?
.htaccess (hypertext access) is a configuration file used by Apache-based web servers. It is employed at the directory level and is primarily used by WordPress to manage permalinks and redirect rules. The .htaccess file enables website administrators to set server configurations for the directory in which the file is placed and all its sub-directories.
Can I use .htaccess to improve the performance of my WordPress site? If yes, how?
Yes. Use .htaccess to enable server-side and browser caching of your site’s content. You can also enable Gzip compression with the following code:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
How do I fix the WordPress permalinks issue with .htaccess?
There are several ways you can use .htaccess to fix WordPress permalink issues. The first is navigating to Settings > Permalinks switching to a different permalink structure (and saving it) and switching back to your original permalink structure (and saving it again).
Next, check that your .htaccess file is writable; its permissions should ideally be set to 644. If you’re struggling to change the .htaccess file’s permissions, ask your host for assistance.
One common reason we’ve found people tend to have problems with their permalinks (if any of the above doesn’t work) is because mod_rewrite hasn’t been enabled (common, especially on freshly installed servers), or because the AllowOverride directive in the Apache configuration needs to be set to All.
As a final resort, you can replace the content in your .htaccess file with the default WordPress rewrite rules. Keep in mind that this will restore your .htaccess file to its original state. Settings added by plugins will be lost unless backed up safely.
Default WordPress rewrite rules:
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
What is the correct way to edit the .htaccess file for a WordPress site without breaking the site?
The best way to edit the .htaccess file is safely on a development or staging site since even the smallest syntax errors can lead to downtime. These tips will also help you reduce risk while working on your .htaccess file:
- Make frequent backups of your .htaccess file, with the first being before you make any changes. Alternatively, keep a log of all the changes you make.
- If you’ve downloaded your .htaccess file to work on it on your computer before uploading it again, use plain text editors (e.g. Notepad, Notepad++, Sublime, etc.) and avoid word processors like MS Word since they can corrupt the file.
- Test your entire site after you’ve uploaded the modified .htaccess file
Can .htaccess be used to fix the mixed content warning on a WordPress HTTPS site? How?
Mixed content warnings occur when a site served over HTTPS loads resources (like images, scripts, or stylesheets) over an insecure HTTP connection. .htaccess can be used to fix the mixed content warning on a WordPress HTTPS site by forcing HTTPS for all requests. Here’s how:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]
Don’t feel like doing all the tech heavy lifting?
The .htaccess file can be used to secure your WordPress site by blocking IP addresses and preventing file and folder browsing. It can also help optimize performance with both server-side and client-side caching and prevent hotlinking of your digital media assets. That’s just the tip of the iceberg.
But maybe all this tech stuff isn’t really where your passions lie, or perhaps you just don’t have the time. At SunnyHQ we’ve got the passion, time, and technical know-how to take care of your site the way you want it. Check out some of our website maintenance packages here.