WordPress .htaccess File – Optimization 2022

WordPress .htaccess file: How to use the .htaccess file

WordPress .htaccess file: the .htaccess file is an important WordPress core file that is often used to add, modify, and override server-level configurations, security, and performance parameters.

What is a .htaccess file?

A .htaccess file is the heart of your website, which contains basic rules that govern all communication with your WordPress and web hosting. Specifically, you can use the .htaccess file in WordPress for tasks like controlling access to web pages, improving security, and performance.

But be careful!
A single misplaced dot (.) can potentially crash your site. So before you make any changes to the .htaccess file, save the file to an external location first. If something goes wrong or you need help, contact your web hosting provider or a savvy webmaster.

The default .htaccess file in WordPress

The .htaccess file comes with every WordPress installation and is generally located in the root directory. Given the importance of the file, it is often hidden (it has no file extension) and does not appear in the file and folder lists, mainly because the file manager hides it for security reasons.

In rare cases, it is possible that there is no .htaccess file in the root folder. If this is the case for you, you can create a .htaccess file in WordPress using Notepad (or any text editor of your choice) and save it under the name “.htaccess”. Set the “File Type” to “All Files” and upload them to the root directory of your WordPress installation.

IMPORTANT: Make sure that the file name is NOT “htaccess” without (.) – but .htaccess with a period (.) at the beginning.

Here’s what the default .htaccess file for WordPress looks like:

# 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

If the .htaccess file doesn’t already exist in your root directory, you can create it in the WordPress dashboard under: -> Settings -> Permalinks and then click on “Save changes” as shown in the image below. This will generate the default .htaccess file for WordPress in the root directory.

permalinks
Create the .htaccess file in the WordPress dashboard.

WordPress’ default .htaccess file only handles permalinks from your website. However, this can be changed and additional rules can be added. This allows you to control how the Apache web server handles operation-related requests.

How do I edit a .htaccess file in WordPress?

To edit the .htaccess file in WordPress, go to your root directory. You can do this via the file manager provided by your WordPress provider or hoster, or via an FTP client like FileZilla.

Log in to your web hosting account and navigate to the “public_html” folder and look for the .htaccess file in the WordPress installation.

JoeWP - .htaccess file on the server
File .htaccess file in the root directory of WordPress

Right-click on the file, then click the “View/Edit” option to open it in your favorite text editor. Edit the necessary changes and save the file.

Another way to edit the WordPress .htaccess file is to make a copy on the local system. When you’re done, replace the live version via FTP or the file manager.

WordPress .htaccess Redirects

As shown above, the .htaccess file in WordPress can be used to control website redirects. Here are some commonly used rules to help you set up and control redirects on your WordPress websites.

301 (permanent) redirect

A 301 redirect tells search engines that a URL has been permanently moved to another location. This isn’t just limited to URLs, and you can redirect a folder, a page, or even an entire website. The following snippet redirects the alteseite.html to neueseite.html:

Redirect 301 /alteseite.html http://www.ihrewebsite.com/neueseite.html

302 (temporary) redirect

Unlike 301, the 302 redirect tells search engines that this redirect is temporary. This is a great way to slow down (or even prevent) SERP shuffles. Add the following line to the .htaccess file:

Redirect 302 /alteseite.html http : //www.ihrewebsite.com/neueseite.html

Force URL on www

The following .htaccess rule in WordPress redirects all visitors from example.com to: 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 .htaccess rule redirects all visitors from www.example.com to example.com.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Enforce HTTPs

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

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Enforce HTTP

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

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} ^https$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}</IfModule>

Redirect domain to subdirectory

The following rule redirects the root URL of the domain to the subdirectory of your choice.

RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{REQUEST_URI} !^/sub-directory-name/
RewriteRule (.*) /subdir/$1

Redirect URL

If you have two domains serving the same website, the .htaccess rule mentioned below will redirect one domain to the other.

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

WordPress .htaccess Security Tips

The .htaccess file can also be used to back up WordPress directories and WordPress files to the server. Here are a few very important rules that users can apply to secure WordPress websites.

How can I protect the .htaccess?

The .htaccess file can potentially control the entire website. With this in mind, it is paramount that the .htaccess is protected from unauthorized users. You can use the following snippet to restrict access for all unauthorized users.

Just copy the snippet and paste it into the .htaccess file.

<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>

How can I restrict access to the WordPress admin panel?

Imagine the (terrible) scenario of someone gaining access to your WordPress admin panel. Such an attack can cause extreme damage or completely destroy your website.

To prevent this from happening, you can restrict access to the WordPress admin panel to only a specific IP(s).

To do this, create another .htaccess file and paste the following snippet into it. Next, upload it to the “www.yourwebsite.com/wp-admin/” folder via FTP.

# Limit logins and admin by IP
<Limit GET POST PUT>
order deny,allow
deny from all
allow from xx.xx.xx.xx
</Limit>

Hint: Don’t forget to replace “xx.xx.xx.xx” in the code above with your allowed IP address.

Now, if someone isn’t on the approved IP list, they won’t be able to log in to your site. Instead, the following error would be displayed:

internal server error

How can I back up important files?

You can use the .htaccess file in WordPress to protect important files like error logs, wp-config.php, and php.ini. Use the following snippet:

<FilesMatch "^.*(error_log|wp-config\.php|php.ini|\.[hH][tT][aApP].*)$">
Order deny,allow
Deny from all
</FilesMatch>

How can I protect the file wp-config.php?

In your WordPress installation, the file is wp-config.php the file that stores the hosting, database, and other important credentials. It is therefore existential that this file is protected from any unauthorized access.

To do this, simply copy the following lines and paste them into your .htaccess file.

<files wp-config.php>
order allow,deny
deny from all
</files>

How can I protect the /wp-content/ folder?

The “wp-content” folder contains all the important files of your theme, the plugins, the media and cached files. That’s why this directory is the main target of hacker attacks and spammers especially like to use it. 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>

The above rule would only allow users to upload files with the allowed extensions (XML, CSS, JPG, JPEG, PNG, GIF, and JavaScript). All other file types will be rejected.

How can I protect wp-includes files?

Some areas of your WordPress installation should never be accessible to the average user. It is always recommended to block all access to these files. You can set up the access restrictions by adding the following snippet to your .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>

How can I disable PHP execution?

Restricting the execution of PHP code for all or selected directories of the WordPress website is an important security practice. Create an htaccess file in a folder where you don’t want to run PHP scripts and add the following snippet.

<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 in these directories.

How can I restrict file access?

Restricting access to wp-admin is an important requirement, especially when multiple team members are involved in managing and updating the site.

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

.htaccess is a great way to protect direct access to edit PHP files from plugins and themes, making it harder for hackers to inject malicious code. To do this, simply 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]

How can I provide injection protection for scripts?

Script injection is a notorious technique in which the attacker “injects” malicious code into the website code in order to extract data or take over the website. Adding the following snippet to the WordPress file “.htaccess” can protect your website 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]

How can I block my IP address?

If someone abuses your site, continuously spams, or starts hacking attempts, their IP will be visible in the WordPress admin area. To block the IP, simply use the .htaccess file to control access to your website. Just copy the following snippet and paste it into the .htaccess file. This will fix this particular problem immediately. Remember to replace the sample IP with the spammer’s.

<Limit GET POST>
order allow,deny
deny from 123.456.78.9
allow from all
</Limit>

How can I deny access to certain files?

Want to restrict access to specific files? No problem. Use the following .htaccess rule to block access to individual files.

<files your-file-name.txt>
order allow,deny
deny from all
</files>

How can I disable directory search?

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

Adding the following snippet to your .htaccess file can control and/or disable access to website directories for all users.

# disable directory browsing
Options All -Indexes

htaccess rules for performance improvement

The .htaccess file in WordPress can also be used to improve the performance/performance of your website. Just copy and paste the relevant snippets into the .htaccess file

How can I activate the browser cache?

The browser cache is a temporary storage space on your system for the files downloaded from your web browser to render websites properly. These files can contain HTML, CSS, JavaScript, as well as images and other multimedia content.

In WordPress’ .htaccess file, you can set rules for how long certain files should be cached. The following expiration limits are set based on common usage. To enable browser caching, paste the following snippet into the htaccess file.

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

How can I enable Gzip compression?

Gzip is an extremely powerful compression algorithm that finds similar strings in a text file and temporarily replaces them. This will significantly reduce the overall size of the file. For this reason, Gzip is often used as an important tool for optimizing website page load speed .

Gzip compression is often used at the server level, and many hosting providers enable it by default. In some cache plugins, such as “WP Rocket“, corresponding code is automatically inserted. You can then check this in your .htaccess file. However, if for some reason that doesn’t work, you can add the following snippet to the .htaccess file.

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

How can I control/restrict image hotlinking?

Image hotlinking can significantly affect bandwidth usage because every time an external resource requests an image, your server bandwidth is used to serve the image.

To reduce bandwidth consumption due to image hotlinks, 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]

htaccess for WordPress Multisite (WPMU)

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

Default htaccess for WPMU subfolders

If your WordPress multisite network is based on subfolders, the default .htaccess file should look something like this:

RewriteEngine On
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]

Standard htaccess for WPMU SubDomains

If your WordPress multisite network is based on subdomains, the default .htaccess file should look something like this:

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]

Conclusion

When it comes to server configuration, the WordPress .htaccess file is one of the most important files on your server. It’s often used to configure your web server and to secure and optimize different areas of your website.

JoeWP WordPress Agency - Request

You want us to optimize the .htaccess file in WordPress?