This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Introducing DigitalOceans General Purpose & CPU Optimized Servers on Cloudways Flexible. Learn More

How to Use WordPress .htaccess File to Secure, Optimize, and Control Redirects

Updated on February 17, 2025

20 Min Read
htaccess wordpress

Key Takeaways:

  • The .htaccess file is a powerful tool for WordPress, enabling control over redirects, security, and performance, but it requires careful handling due to its sensitivity.
  • Mastering .htaccess can significantly improve your WordPress site, from SEO-friendly URLs and robust security measures to improved performance through caching and compression.

The .htaccess file is a crucial WordPress core file that allows you to modify server-level configurations, security settings, and performance parameters.

When you install WordPress for the first time, it creates various directories like wp-admin, wp-content, and wp-includes to keep your site running. WordPress also creates the .htaccess file, which works as a configuration file that tells your server how to handle different requests.

In easier words, you can use the .htaccess file to clean up URLs for SEO, set up automatic redirects, improve security by blocking unauthorized access, and optimize performance with caching rules.

However, many website owners are unaware of this file’s actual potential and miss out on optimizing their servers (and websites) to the fullest.

To assist WordPress users, this guide will explain how to find and edit the .htaccess file within WordPress, including various rule applications.

What Is a WordPress .htaccess File?

A .htaccess file is the control room for your website, containing essential rules that govern all communication with your WordPress web hosting server.

You can find the .htaccess files in the main directory of your WordPress installation. WordPress uses these files to handle default tasks like managing redirects and setting up permalink structures.

In particular, the .htaccess file (also known as a directory-level configuration file) in WordPress allows you to perform various tasks, such as setting up redirects, rewriting URLs for SEO, enabling hotlink protection, restricting access to specific files, and improving security and performance through features like caching and compression.

Many WordPress plugins, especially security and caching plugins, also rely on this file to perform their functions, often adding rules for things like preventing unauthorized access or enabling caching. This is the reason why you’d see # Begin GzipofBreezeWPCache written in the screenshot of my .htaccess file.

You can place the .htaccess in any website’s folder to change the behavior of that folder.

This is what the .htaccess file of my server looks like:

example htaccess file from cloudways

Warning!

A single misplaced dot (.) can potentially bring your website down. Thus before making any changes to the .htaccess file, back it up to an offsite location. Contact your hosting provider if anything goes wrong or if you need assistance.

Fastest WordPress Hosting For Developers & Agencies at just $11/Month*

Experience blazing fast server speeds with Cloudways LAMP + NGINX hybrid stack. Improve your Core Web Vitals and supercharge your WordPress with Cloudways Hosting.

How to Locate the WordPress .htaccess File?

WordPress officially recommends NGINX and Apache for running your sites. If your WordPress site runs on NGINX, you will see no .htaccess file as it doesn’t use this file.

But, if your WordPress site is hosted on an Apache Web Server, you will find the .htaccess file in the root directory (public_html or www).

FileZilla FTP Method to Locate the .htaccess WordPress File

  • To access your .htaccess file, connect your server via an FTP Client like FileZilla and go to your application’s root folder. In my case, the root path is “/applications/mamxbvhtce/public_html”.

access htaccess file through filezilla ftp

  • If you see no .htaccess file, it might be hidden (it doesn’t have any file extension), mainly because the file manager hides it for security reasons. To access the .htaccess hidden file, go to the server option (in FileZilla) and check the Force Showing Hidden Files option.

force show hidden files in filezilla

cPanel Method to Locate the .htaccess WordPress File

If you use cPanel, here is how you can find your .htaccess file:

  1. Log into your cPanel and access the File Manager, as shown in the image below.

Log into your cPanel and access the File Manager

  1. Click the Settings button in the top right corner of your screen.

Settings button in cpanel

  1. In the popup window that shows up, check “Show Hidden Files (dotfiles)”. This makes sure you can see the .htaccess file, which might be hidden sometimes.

Show Hidden Files (dotfiles) in cpanel

  1. Click Save, and the file should now be visible in the File Manager.

After locating the .htaccess file, you can edit it as needed.

Where Is the Default WordPress .htaccess File Located?

The default .htaccess file is stored in the root directory of your WordPress installation. However, because it is a hidden file, you may not see it immediately.

You can access it using an FTP client like FileZilla or through your hosting control panel’s File Manager (such as cPanel). I’ve covered the steps to do this earlier in this guide.

If the .htaccess file is missing, first check that hidden files are enabled in your File Manager settings. If you still don’t see it, WordPress may not have created it yet—this is common if permalinks haven’t been set up.

In that case, you can manually create a standard WordPress htaccess file:

  1. Open Notepad (or any text editor).
  2. Save the file as “.htaccess” (with a period at the start).
  3. Set “Save as type” to All Files and upload it to the root directory via FTP or File Manager.

Note: Ensure the file is named “.htaccess” and not just “htaccess”. The dot at the beginning is required for it to function.

save htaccess file

The default .htaccess file for WordPress looks like this:

# 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 WordPress

How to Create a WordPress htaccess File?

If you don’t know, the default .htaccess file is not always present in fresh WordPress installations, but WordPress generates it automatically when you set up permalinks. If this is the case for you, you can easily do this through your WordPress admin dashboard.

To generate the .htaccess file manually:

  • Visit the WordPress Dashboard.
  • Click Settings > Permalinks.
  • Click the Save Changes button.

create the .htaccess file

After doing this, WordPress will create the .htaccess file inside the root directory of your website. By default, this file only manages permalinks, but you can modify it to add custom rules for things like redirects, caching, security, and other Apache server operations.

Of course, this isn’t the only way to create a .htaccess file. You can also create a file manually directly in the cPanel (if you use cPanel) or create one using a text editor like I showed you earlier and upload it to your web server using an FTP client like FileZilla.

For cPanel

  • Log in to your cPanel account.
  • Open File Manager from the Files section, as I showed you earlier.

Log into your cPanel and access the File Manager

  • Once inside, click the +File button on the top-left.

add new htaccess file in cpanel

  • When a small window pops up, type .htaccess as the file name and select the folder where you want to create it.

Create New htaccess File in cpanel

  • Click Create New File to save it.

For SFTP

If you prefer this method, like I showed you earlier, create a new file. Make sure you name it “.htaccess” and not “htaccess”. In the file, paste this code:

# 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 WordPress

Note: You can add additional rules to the file you created based on security, caching, or performance requirements.

After saving the file, use any SFTP client of your choice. I’m using FileZilla for this example. Simply drag and drop the file to the folder where you want to create it. I’ll put this file in the public.html folder.

upload new htaccess file using filezilla

.htaccess edits gone wrong?

Swap security tweaks and redirect rules with WordPress pros on our Reddit.

How to Edit the .htaccess File in WordPress?

To edit the .htaccess file in WordPress, go to your root directory using the file manager provided by your WordPress hosting provider. You may also use an FTP client like FileZilla.

  • Log in to your FTP client.
  • Navigate to the ‘public_html’ folder and look for the .htaccess file.

.htaccess file

  • Right-click and click on the ‘View/Edit’ option to open it in your preferred text editor.

‘View/Edit’ option

  • Make the required changes and save the file.

Another way of editing the WordPress .htaccess file is to make a copy in the local system. Once you are done, replace the live version using FTP or file manager.

replace old htaccess file with new file

How to Edit .htaccess WordPress Using cPanel?

If you prefer an alternative to the FTP method described earlier, you can use cPanel available in your hosting account. Here are the steps to edit the .htaccess file in WordPress using cPanel:

  • Access Control Panel: Log in to your hosting account’s control panel.
  • Open File Manager: Within the control panel, locate and open the “File Manager” tool.
  • Navigate to public_html: In the left-hand navigation menu, click on the “public_html” folder, which is the main directory of your website.
  • Locate WordPress Folder: Within the “public_html” directory, locate and open the “wordpress” folder where your WordPress installation resides.

Edit .htaccess WordPress Using cPanel

  • Find the .htaccess File: Inside the “wordpress” folder, you’ll find the .htaccess file. Right-click on it to initiate the editing process.
  • Edit .htaccess File: Select the option to edit the .htaccess file. A text editor will open within your browser.
  • Add Code: Introduce any code you wish to implement, ensuring that you place it before the line that reads “# BEGIN WordPress.”

By following these steps, you can effectively modify your WordPress site’s .htaccess file using cPanel.

Fully Managed WordPress Hosting That Autoscales

Manage your WordPress site with ease on Cloudways Autonomous. Get fast, secure hosting that scales with your traffic—all without any setup headaches.

How to Edit .htaccess WordPress Using a Plugin?

Another approach to editing the .htaccess file is by using a WordPress plugin such as Htaccess File Editor. Plugins like this let you edit the .htaccess file directly within the WordPress backend.

Edit .htaccess WordPress Using a Plugin

Here’s how you can edit your .htaccess file in WordPress using the Htaccess File Editor plugin:

  • Log in to your WordPress admin dashboard.
  • Search for the “Htaccess File Editor” plugin from the WordPress plugin repository.
  • Install and activate the plugin.
  • Within the dashboard, go to “Settings” and then select “WP Htaccess Editor.”
  • As a preliminary step, insert a new line just before the “# BEGIN WordPress” section in the .htaccess file.
  • And that’s it. You can add any code snippets to define your desired rules or configurations.

How to Set WordPress .htaccess Redirects?

You can use the .htaccess file in WordPress to control website redirects. Below are some frequently used rules that help you set up and control redirections on your WordPress websites.

301 (Permanent) Redirect

A 301 Redirect tells search engines that a URL has been permanently moved to another location. This is not limited to URLs only; you can also redirect a folder, page, or even a complete website. The following snippet will redirect the oldpage.html to newpage.html:

Redirect 301 /oldpage.html https://www.yourwebsite.com/newpage.html

302 (Temporary) Redirect

Unlike 301, the 302 Redirect tells search engines that the redirection is temporary. Using 302 redirect helps you slow down (or even prevent) SERP shuffles.

Add the following line to the .htaccess file:

Redirect 302 /oldpage.html http://www.yourwebsite.com/newpage.html

Force URL to www

The following .htaccess rule in WordPress will force all the visitors on example.com to use www.example.com

RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com [NC]

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Force URL to non-www

The following WordPress .htaccess rule will force all visitors on www.example.com to use example.com

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www.example.com [NC]

RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Force HTTPS

The following rule in the WordPress .htaccess file will force all your visitors to use HTTPS instead of HTTP for all URLs.

RewriteEngine On

RewriteCond %{HTTPS} off

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

Read more: Learn how to add an SSL certificate to a WordPress website.

Force HTTP

The following rule in the .htaccess file forces your visitors to use HTTP instead of HTTPS for all URLs.

RewriteEngine On

RewriteCond %{HTTPS} on

RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

WordPress htaccess Redirect With Directory

The following rule will redirect the domain’s root URL to the subdirectory of your choice.

RewriteCond %{HTTP_HOST} ^example.com$

RewriteCond %{REQUEST_URI} !^/sub-directory-name/

RewriteRule (.*) /subdir/$1

Redirect a URL

If two domains serve the same website, the below-mentioned .htaccess rule will redirect one domain to the other.

Redirect 301 / http://www.mynewwebsite.com/

Redirect a Post or Page

If you want to redirect a single post or page, you can add the following line of code for any post or page you want to redirect:

Redirect 301 /old-url-slug https://yourdomain.com/new-url-slug

Let’s say you’d like to redirect “https://www.cloudways.com/blog/core-web-vitals/” to “https://www.cloudways.com/blog/core-web-vitals-seo/”. Then, you would add the following line of code in the .htaccess file:

Redirect 301 /core-web-vitals/ https://www.cloudways.com/blog/core-web-vitals-seo/

The old URL will now redirect everyone who clicks on an internal or external link to the new URL.

Redirect Your Entire Site

If you want to redirect your entire website to a new domain, you can add the following code snippet to the .htaccess file in WordPress:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^olddummydomain.com [NC,OR]

RewriteCond %{HTTP_HOST} ^www.olddummydomain.com [NC]

RewriteRule ^(.*)$ https://newdummydomain.com/$1 [L,R=301,NC]

Replace the dummy text in the code above with your old and new domain names.

To make you better understand: Imagine you had a website called www.oldwebsite.com/about. With the changes we’ve made, anyone who goes to that link will be taken to the new page atwww.newwebsite.com/about.

Join 12,000+ Agencies Loving Our Managed WordPress Hosting!

Say goodbye to the need for an in-house IT team. Opt for Cloudways and experience lightning-fast hosting, expert 24x7x365 support, and the performance your clients expect from your agency

WordPress .htaccess Security Tips

Since WordPress is an open-source platform, its sites remain vulnerable to security breaches. Therefore, users must take proactive steps, such as opting for a credible web host like Cloudways that prioritizes their website security and remain protected against malicious traffic and DDoS attacks.

Cloudways Flexible and Autonomous, both are provided with Cloudflare Enterprise, SafeUpdates, and Vulnerability scanner, ensuring a safe online presence.

You can also secure your WordPress directories and files via the .htaccess file. Follow the following rules to secure your WordPress websites.

Protect the .htaccess File

The .htaccess file can potentially control the entire website. So you must also protect your .htaccess from unauthorized users. Restrict access to the .htaccess file by copying/pasting the following snippet into the .htacess file:

<files ~ "^.*\.([Hh][Tt][Aa])">

order allow,deny

deny from all

satisfy all

</files>

Restrict Access to WordPress Admin Panel

If someone gains access to your WordPress admin panel, they can do whatever they want and even shut down your whole website.

To prevent this, you should restrict access to the WordPress admin panel to specific IP(s) only.

  • Create another .htaccess file, and paste the following snippet into it.
# Limit logins and admin by IP

<Limit GET POST PUT>

order deny,allow

deny from all

allow from xx.xx.xx.xx

#whitelist Farhan’s IP Address

</Limit>
  • Upload it to the “www.yourwebsite.com/wp-admin/” folder.

Now, if a user tries to log in to your site with an unapproved IP address, he will see the following error:

internal server error

Note: Don’t forget to replace “xx.xx.xx.xx” with your allowed IP address.

You can easily get your IP by visiting “What Is My IP”. If you’ve got more than one moderator, you can also add multiple IPs by using the following variation:

allow from 34.56.78 98.76.54.32 19.82.73.64

Block Specific User Agents

This rule blocks access to your site for specific user agents (e.g., malicious bots, scrapers, or crawlers).

RewriteCond %{HTTP_USER_AGENT} ^BadBot [NC,OR]

RewriteCond %{HTTP_USER_AGENT} ^AnotherBadBot [NC]

RewriteRule ^.* - [F,L]

Disable XML-RPC

XML-RPC is a feature that allows remote connections to your WordPress site. However, it is often exploited by attackers to:

  • Perform brute-force login attempts.
  • Execute DDoS (Distributed Denial of Service) attacks.
  • Exploit vulnerabilities in plugins or themes.

This rule disables access to the xmlrpc.php file in WordPress.

<Files xmlrpc.php>

Order Deny,Allow

Deny from all

</Files>

Secure Important Files

You can use .htaccess in WordPress to protect important files such as functions.php, wp-config.php, and php.ini, by using the following snippet:

<FilesMatch "wp-config\.php|php.ini|functions\.php">

Order deny,allow

Deny from all

</FilesMatch>

Protect the wp-config.php File

In WordPress, wp-config.php is the file where the hosting, database, and other important credentials are saved. So, you must protect the file from all unauthorized access.

Copy and paste the following lines into the .htaccess file:

<files wp-config.php>

order allow,deny

deny from all

</files>

Protect the wp-content Folder

The wp-content folder contains all the important themes, plugins, media, and cached files, making it the main target of hackers and spammers.

To protect this folder from unauthorized access, create a separate .htaccess file in the wp-content folder. Next, copy and paste the following snippet into the file:

Order deny,allow

Deny from all

<Files ~ ".(xml|css|jpe?g|png|gif|js)$">

Allow from all

</Files>

With the above rule, users would only be able to upload files with the allowed extensions (XML, CSS, JPG, JPEG, PNG, GIF, and JavaScript), denying all other file types.

Protect Include-Only Files

Some areas of the WordPress installation should never be accessible by the average user. The best practice is to block all access to these files, and you can set up the access restrictions by adding the snippet to the .htaccess file.

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /

RewriteRule ^wp-admin/includes/ - [F,L]

RewriteRule !^wp-includes/ - [S=3]

RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]

RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]

RewriteRule ^wp-includes/theme-compat/ - [F,L]

</IfModule>

Disable PHP Execution

Restricting the execution of PHP code for all or selected directories of your site is a critical WordPress website security practice. Create a .htaccess file inside a folder where you don’t want to run PHP scripts and add the snippet below.

<Files *.php>

deny from all

</Files>

Certain WordPress folders, such as wp-includes and /wp-content/uploads/ are writable by default. This type of permission allows users to upload media or different file types. It is always recommended to disable PHP execution on these directories.

File Access Restriction

Restricting access to wp-admin is an important requirement, mainly when several team members are involved in website management and updates.

In practical terms, this means that the users cannot access sensitive files such as plugins, themes, and assets folders.

.htaccess is a great way of protecting direct access to edit PHP files of WordPress plugins and themes, making it harder for hackers to inject malicious code. For this, just add the following lines to the file:

RewriteCond %{REQUEST_URI} !^/wp-content/plugins/file/to/exclude\.php

RewriteCond %{REQUEST_URI} !^/wp-content/plugins/directory/to/exclude/

RewriteRule wp-content/plugins/(.*\.php)$ - [R=404,L]

RewriteCond %{REQUEST_URI} !^/wp-content/themes/file/to/exclude\.php

RewriteCond %{REQUEST_URI} !^/wp-content/themes/directory/to/exclude/

RewriteRule wp-content/themes/(.*\.php)$ - [R=404,L]

Script Injection Protection

Script injection is a notorious technique in which the attacker “injects” a malicious piece of code into the website code to extract data or take over the website.

Adding the following snippet in the WordPress .htaccess file can protect your site from such attacks.

Options +FollowSymLinks

RewriteEngine On

RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]

RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]

RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})

RewriteRule ^(.*)$ index.php [F,L]

Block IP Address

If someone is abusing your website, continuously spamming, or launching hacking attempts, their IP is visible in the WordPress admin panel. You can block the IP using the .htaccess file and restrict their access to your website.

Simply copy & paste the following snippet into your site’s .htaccess file to block IPs. Remember to replace the sample IP with the spammer’s IP.

<Limit GET POST>

order allow,deny

deny from 456.78.9

allow from all

</Limit>

Once the snippet is in place, the spammer will see the following error message on your site:

Forbidden error

Deny Access to Certain Files

Sometimes, you want to restrict access to certain files. And you can do it by using the following .htaccess rule.

<files your-file-name.txt>

order allow,deny

deny from all

</files>

Disable Directory Browsing

Unauthorized access to website files and folders is a major security risk that can potentially bring down the entire site.

You can control access to website directories by adding the following snippet to your WordPress .htaccess file:

# disable directory browsing

Options -Indexes

WordPress .htaccess Rules for Performance

You can use the .htaccess file in WordPress to enhance your website performance. Just copy & paste the relevant snippets in the .htaccess file.

Enable Browser Cache

The browser cache is temporary storage on your system for the files downloaded by your web browser to render websites correctly. These files may include HTML, CSS, JavaScript, images, and other multimedia content.

You can set rules for how long specific files should be cached, and those limits are set based on popular usage. Add the following snippet in the .htaccess file for WordPress to enable browser caching.

<IfModule mod_expires.c>

ExpiresActive on

ExpiresDefault "access plus 1 month"




# CSS

ExpiresByType text/css "access plus 1 year"




# Data interchange

ExpiresByType application/json "access plus 0 seconds"

ExpiresByType application/xml "access plus 0 seconds"

ExpiresByType text/xml "access plus 0 seconds"




# Favicon (cannot be renamed!)

ExpiresByType image/x-icon "access plus 1 week"




# HTML components (HTCs)

ExpiresByType text/x-component "access plus 1 month"




# HTML

ExpiresByType text/html "access plus 0 seconds"




# JavaScript

ExpiresByType application/javascript "access plus 1 year"




# Manifest files

ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"

ExpiresByType text/cache-manifest "access plus 0 seconds"




# Media

ExpiresByType audio/ogg "access plus 1 month"

ExpiresByType image/gif "access plus 1 month"

ExpiresByType image/jpeg "access plus 1 month"

ExpiresByType image/png "access plus 1 month"

ExpiresByType video/mp4 "access plus 1 month"

ExpiresByType video/ogg "access plus 1 month"

ExpiresByType video/webm "access plus 1 month"




# Web feeds

ExpiresByType application/atom+xml "access plus 1 hour"

ExpiresByType application/rss+xml "access plus 1 hour"




# Web fonts

ExpiresByType application/font-woff2 "access plus 1 month"

ExpiresByType application/font-woff "access plus 1 month"

ExpiresByType application/vnd.ms-fontobject "access plus 1 month"

ExpiresByType application/x-font-ttf "access plus 1 month"

ExpiresByType font/opentype "access plus 1 month"

ExpiresByType image/svg+xml "access plus 1 month"




</IfModule>

Read more: Learn how to Leverage Browser Caching in WordPress to Optimize Page Load Time

Limit File Upload Size

This rule restricts the maximum file size that users can upload to your site.

php_value upload_max_filesize 10M

php_value post_max_size 10M

I’ve covered a guide on how to increase the maximum upload limit in WordPress that you might find helpful.

Enable Gzip Compression

Gzip is a powerful compression algorithm that locates similar strings within a text file and replaces them temporarily to reduce the overall file size.

It functions similarly to Brotli compression. You can check out our Brotli vs. Gzip compression guide for better understanding. Anyway, Gzip is used as an important website page load speed optimization tool.

Gzip compression is often used on the server level, and many hosting providers like Cloudways have it enabled by default. However, if .htaccess is not working, add the following snippet to the WordPress .htaccess file or contact your web hosting provider:

<IfModule mod_deflate.c>




# Compress HTML, CSS, JavaScript, Text, XML and fonts

AddOutputFilterByType DEFLATE application/javascript

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




# Remove browser bugs (only needed for really old browsers)

BrowserMatch ^Mozilla/4 gzip-only-text/html

BrowserMatch ^Mozilla/4\.0[678] no-gzip

BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

Header append Vary User-Agent




</IfModule>

Control/Restrict Image Hotlinking

Image hotlinking can significantly affect bandwidth usage because whenever an external resource requests an image, your server bandwidth is utilized to deliver the image.

To reduce bandwidth consumption because of image hotlinking, you can add the following code snippet to the .htaccess file:

RewriteEngine on

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]

RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Think You’re Paying Extra Hosting Costs?

Steer clear of what you pay for your hosting needs. The Web Hosting Savings Calculator helps you instantly find out the right cloud hosting solution based on your requirements.

.htaccess for WordPress Multisite (WPMU)

The default .htaccess file for WordPress Multisite is slightly different from the standard WordPress .htaccess file.

Default .htaccess for WPMU Subfolders

If your WordPress Multisite network is subfolders-based, the default .htaccess file should look like this:

# BEGIN WordPress Multisite

# Using subfolder network type: https://wordpress.org/support/article/htaccess/#multisite




RewriteEngine On

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteBase /

RewriteRule ^index\.php$ - [L]




# add a trailing slash to /wp-admin

RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]




RewriteCond %{REQUEST_FILENAME} -f [OR]

RewriteCond %{REQUEST_FILENAME} -d

RewriteRule ^ - [L]

RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]

RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]

RewriteRule . index.php [L]




# END WordPress Multisite

Default .htaccess for WPMU SubDomains

If your WordPress Multisite network is subdomain based, the default .htaccess file should look like this:

# BEGIN WordPress Multisite

# Using subdomain network type: https://wordpress.org/support/article/htaccess/#multisite




RewriteEngine On

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

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]




# END WordPress Multisite

Troubleshooting Common .htaccess WordPress Issues

1. Syntax Errors in .htaccess

A single syntax error, such as a missing bracket, incorrect directive, or misplaced character, can prevent your site from functioning.

Solution: Use an .htaccess validator like htaccess-check to identify errors. Correct the highlighted mistakes and upload the fixed file.

2. mod_rewrite Not Enabled

If your URL redirections aren’t working, it’s often because Apache’s mod_rewrite module is not enabled.

Solution: Run sudo a2enmod rewrite in your terminal and then restart Apache with sudo systemctl restart apache2.

3. Incorrect File Naming or Placement

If your .htaccess rules are not applying, the file might be misnamed or misplaced.

Solution: Ensure the file is named .htaccess (with a leading dot, no extension) and placed in the root directory of your WordPress installation.

4. Unidentified Errors Causing Site Issues

Your site may show errors or fail to load without a clear reason.

Solution: Check the Apache error logs at /var/log/apache2/error.log to pinpoint the cause and make necessary corrections.

5. Unresponsive Site Due to .htaccess

An incorrect .htaccess configuration can make your entire site inaccessible.

Solution: Temporarily rename the .htaccess file (e.g., .htaccess_backup). If the site works, revert and edit the file line by line to find the problematic directive.

Final Thoughts!

The WordPress .htaccess file is essential for managing redirects, securing critical files like wp-config.php, and optimizing site performance through browser caching and Gzip compression. In this guide, we’ve explored how to locate, create, and edit the .htaccess file using cPanel and plugins, implement various redirect rules, and apply security measures to protect your WordPress site.

We’ve also covered performance-enhancing rules and settings for WordPress Multisite installations. If there’s an important .htaccess use case I’ve missed, share it in the comments, and I’ll update the guide accordingly.

Frequently Asked Questions

Q. What is the .htaccess file in WordPress?

The .htaccess file in WordPress is a configuration file used by Apache web servers to control various settings on a per-directory basis. WordPress utilizes this file to manage how URLs are handled, especially for enabling pretty permalinks, which make your URLs cleaner and more SEO-friendly. It can also be used to enhance security, redirect traffic, and optimize server performance.

Q. How do I edit the .htaccess file in WordPress?

To edit the .htaccess file in WordPress, access your site’s files through an FTP client or your hosting provider’s file manager. Locate the .htaccess file in the root directory of your WordPress installation. Open the file with a text editor, make your changes, and save it. Once updated, upload the file back to the server and test your site to ensure the changes take effect.

Q. Does WordPress create a .htaccess file?

Yes, WordPress automatically creates a .htaccess file, typically in the root directory. If you can’t find it, go to your WordPress dashboard, navigate to Settings > Permalinks, and click “Save Changes.” This will regenerate the .htaccess file with the correct default rules.

Q. Is .htaccess necessary for WordPress?

Yes, the .htaccess file is necessary for WordPress to function properly, especially for handling pretty permalinks (custom URL structures) and enabling features like redirects and security settings. While WordPress can run without it, many essential functions depend on the .htaccess file for optimization and security.

Q. What is the default .htaccess file for WordPress?

The default .htaccess file for WordPress is automatically created in the root directory of your website. If you’re using Apache as your web server, you’ll find it in the root folder (commonly public_html or www). By default, the file includes basic settings for pretty permalinks, ensuring your URLs are clean and user-friendly. It’s an important file for proper WordPress functionality and can be edited to enhance site performance and security.

Q. What is the purpose of the .htaccess file in WordPress?

The .htaccess file in WordPress is a powerful configuration file that controls how your server handles your website. It helps manage things like setting up 301 redirects, enabling SSL connections for secure browsing, adding password protection, and defining the default language for your site. In short, it plays a key role in improving your site’s performance, security, and user experience.

Q. What common directives or rules are used in the WordPress .htaccess file?

Common directives in the WordPress .htaccess file include setting up clean permalink structures, handling redirects, enabling password protection, preventing directory browsing, customizing error pages, blocking specific IP addresses, and enabling GZIP compression for faster site loading. These rules help optimize your website’s security, user experience, and performance.

Q. Are there any security-related settings or configurations in the WordPress .htaccess file?

Yes, the .htaccess file in WordPress can boost your site’s security with several configurations. For instance, it can block directory browsing to prevent unauthorized file access, restrict access to sensitive files like wp-config.php, and limit admin area access to specific IP addresses. These simple steps can significantly reduce the risk of attacks on your website.

Q. What are some best practices for optimizing the .htaccess file in WordPress?

To optimize your .htaccess file in WordPress, enable compression to speed up page loads, set up browser caching to reduce load times, and implement 301 redirects for better SEO. It’s also important to secure the file itself by restricting access, prevent directory browsing, and increase PHP memory limits to avoid performance issues. These steps ensure that your site runs smoothly, securely, and efficiently.

Q. Can I use the .htaccess file to enable or disable certain features or functionalities in WordPress?

Absolutely! The .htaccess file is essential for managing site performance and security in WordPress. You can enable features like custom redirects, browser caching, and GZIP compression. It can also disable unwanted features, such as directory browsing, and control admin area access for better security. It’s a versatile tool for improving your website’s functionality.

Q. How do I troubleshoot issues with the .htaccess file affecting my WordPress site?

If your site is having issues related to the .htaccess file, start by backing up the file. If problems persist, try renaming or deleting it and then regenerate a fresh .htaccess from your WordPress dashboard. Ensure all the rules are correct and check for conflicting plugins. You can also check permissions to ensure the file is readable and writable. If you’re still stuck, consulting your hosting provider or a professional can help. Also, Check out Ionos competitors.

Q. Are there any tools or plugins available to help manage and modify the .htaccess file in WordPress?

Yes, there are several plugins designed to make managing your .htaccess file easier. Plugins like All In One WP Security & Firewall, WP Htaccess Editor, BulletProof Security, and Htaccess by BestWebSoft allow you to modify, back up, and secure your .htaccess file without needing to access your server directly.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour