The .htaccess file is a crucial part of WordPress, as it may be used to alter or override settings related to the server’s setup, security, and performance. It is common practice to modify the .htaccess file’s rules to fix server-side problems.
Unfortunately, many webmasters fail to realize this file’s full potential and hence fail to fully optimize their servers (and websites). In this blog, we’ll show you how to use the .htaccess file in WordPress to do some cool stuff in the hopes that it’ll be useful for you and other like-minded WordPress users.
Please take note that the below-specified rules and configurations are compatible with Apache 2.4.
Understanding .htaccess File
An.htaccess file acts as the control station for your website, containing the rules that regulate how your site interacts with WordPress’s server.
For instance, the.htaccess file in WordPress can be used to restrict access to specific pages, increase security, and boost site speed. Files with the extension “.htaccess” can be dropped into any website’s folder to alter its operations.
Locating .htaccess in WordPress
NGINX and Apache are officially recommended by WordPress to run the sites. The .htaccess file is not used by NGINX-powered WordPress sites. But, if Apache is hosting your WordPress site, the .htaccess file will be in the root directory (public HTML or WWW).
What you can do is use an FTP, like FileZilla, to connect to your server and navigate to the root folder of your application to locate the .htaccess file. Furthermore, if you cannot locate the .htaccess file (which does not have an extension), it may be hidden for safety reasons within the file manager.
If you want to view the .htaccess file, you’ll need to enable the server-side option to “Force Showing Hidden Files” in FileZilla.
Default WordPress .htaccess File
The .htaccess file, by default, resides in the application root directory and is usually hidden. The file is accessible with an FTP client such as FileZilla. If you can’t find the .htaccess file in the root folder, use Notepad (or another text editor) to create an empty one and store it on your desktop.
Upload the file to your WordPress installation’s root directory using the FTP Client after setting “Save as type” to all files.
WordPress’ default .htaccess file:
# 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
You can check and update the permalink structure by going to Settings > Permalinks in the WordPress dashboard. Saving the permalink twice will regenerate the .htaccess file.
Editing the .htaccess directory File in WordPress
Use your WordPress hosting provider’s file manager to access your root directory and update the .htaccess file. Alternatively, you might use an FTP client like FileZilla.
- Log into the FTP client.
- Check the public_html directory for the .htaccess file.
- Right-click and select “View/Edit” to open in your text editor.
- Save your changes.
One alternative to accessing the original WordPress .htaccess file is to create a local copy for editing. When you are finished, upload the new version to the live server via FTP or a file manager and overwrite the old one.
WordPress .htaccess Redirects
Redirects are managed using the .htaccess file in WordPress. The rules listed below can be used as a starting point for configuring and managing redirects on WordPress sites.
- 301 (Permanent) Redirect
Search engines receive a 301 Redirect when a URL is permanently moved. Not only can you redirect an entire website, but also individual pages, folders, and even just plain old URLs.
If you copy and paste the code below into your oldpage.html file, it will automatically link to your newpage.html.
Redirect 301 /oldpage.html https://www.yourwebsite.com/newpage.html
- 302 (Temporary) Redirect
The 302 Redirect indicates to search engines that the redirection is only temporary, in contrast to the 301 Redirect. A 302 redirect can be used to mitigate or avoid fluctuations in search engine results page rankings.
In the .htaccess file, insert the following line:
Redirect 302 /oldpage.html https://www.yourwebsite.com/newpage.html
- Force URL to www
With the following WordPress .htaccess rule, all visitors to example.com will instead be redirected to www.example.com.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
- Force URL to non-www
All visitors to www.example.com will be redirected to example.com with the use of the following .htaccess rule in WordPress.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
- Force HTTPS
To ensure that all of your site’s visitors use HTTPS rather than HTTP, add the following rule to your WordPress installation’s .htaccess file.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
- Force HTTP
The following line in your .htaccess file will prevent your site from using secure HTTPS connections and instead require all visitors to use insecure HTTP.
RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{REQUEST_URI} !^/sub-directory-name/
RewriteRule (.*) /subdir/$1
- Redirect Domain To Sub-Directory
With this rule, you can point your domain’s root URL to a different directory within your site’s structure.
RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{REQUEST_URI} !^/sub-directory-name/
RewriteRule (.*) /subdir/$1
- Redirect a URL
The following .htaccess rule will point one domain to another if they both host the same website.
Redirect 301 / https://www.mynewwebsite.com/
WordPress .htaccess Security Tips
Sites built with WordPress remain unprotected due to the platform’s open-source nature. Users must take precautions, such as selecting a reliable web host like Nestify, to ensure their sites are safe from malicious traffic and distributed denial of service (DDoS) attacks.
Protecting your WordPress files and folders with the .htaccess file is another option. WordPress sites should be protected by adhering to these guidelines.
- Protecting the .htaccess File
A website’s whole configuration may be stored in the .htaccess file. As a result, you should also secure your .htaccess file to prevent unwanted access. Copy and paste the following code into your .htaccess file to restrict access:
<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>
- Restricting Access to WordPress Admin Panel
If someone manages to get into your WordPress dashboard, they might potentially shut down your entire site.
Protect yourself against this by restricting who can log into the WordPress dashboard.
1. Make a new .htaccess file and add the code below to it.
# Limit logins and admin by IP
<Limit GET POST PUT>
order deny,allow
deny from all
allow from xx.xx.xx.xx
#whitelist ABC’s IP Address
</Limit>
2. Upload it to www.yourwebsite.com/wp-admin/.
- Secure Important Files
Use the following code snippet in your WordPress .htaccess file to restrict access to sensitive files like functions.php, php.ini, and wp-config.php:
<FilesMatch "wp-config\.php|php.ini|functions\.php">
Order deny,allow
Deny from all
</FilesMatch>
- Protect the wp-config.php File
The WordPress configuration file, wp-config.php, stores information on the site’s hosting, database, and other settings. For this reason, you should safeguard the document from intrusion.
Just paste these lines into your .htaccess file:
<files wp-config.php>
order allow,deny
deny from all
</files>
- Protect the wp-content Folder
The wp-content folder is the primary target of hackers and spammers since it contains essential items like themes, plugins, media, and cached data.
Create a new .htaccess file inside the wp-content folder to restrict access to this area. Then, insert the code below into the file:
Order deny,allow
Deny from all
<Files ~ ".(xml|css|jpe?g|png|gif|js)$">
Allow from all
</Files>
- Protect Include-Only Files
The user should never be able to access some parts of the WordPress installation. As a best practice, you should prevent users from accessing these files altogether by adding the code below 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>
- Disable PHP Execution
Take measures to secure your WordPress site by disabling PHP execution in everything but the root directory. If you want to prevent PHP scripts from running in a specific folder, create a .htaccess file there and add the code below.
<Files *.php>
deny from all
</Files>
In WordPress, the wp-includes and /wp-content/uploads/ directories are set to be writable by default. Media and other file types can be uploaded by users with this access. Disabling PHP execution in these folders is a best practice.
- Restrict File Access
In situations when multiple people on a team are responsible for maintaining and updating the website, protecting access to the wp-admin area is crucial.
This effectively prevents users from gaining access to essential system files like plugins, themes, and assets folders.
A .htaccess file can prevent unauthorized users from directly editing the PHP files that power WordPress plugins and themes, making it more difficult for hackers to insert malicious code. You can do this by including the following text in 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
Script injection is a well-known attack vector in which malicious code is “injected” into the website’s code to steal information or seize control of the site.
The following code snippet, when added to your WordPress site’s .htaccess file, will help prevent 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]
- Blocking IP Address
The WordPress control panel will show the IP address of the person who is abusing your site, spamming it repeatedly, or attempting to hack it. With the .htaccess file, you can prevent the IP from accessing your site.
You may easily prevent specific IP addresses from accessing your site by adding the following code to your .htaccess file. The spammer’s IP address should be substituted for the sample IP address.
<Limit GET POST>
order allow,deny
deny from 456.78.9
allow from all
</Limit>
Once the above code is executed, the following message will be displayed:
- Deny Access to Certain Files
In some cases, you may wish to limit who can access particular files. This is easily accomplished using the following .htaccess code.
<files your-file-name.txt>
order allow,deny
deny from all
</files>
- Disabling Directory Browsing
The loss of website integrity due to unauthorized access to its files and folders is a serious security concern.
This code snippet, when inserted into your WordPress .htaccess file, allows you to restrict access to specific directories on your website.
# disable directory browsing
Options -Indexes
WordPress .htaccess Rules for Performance
If you’re using WordPress, you may optimize your site’s speed by editing the .htaccess file. Simply cut and paste the required code into the .htaccess file.
- Enabling Browser Cache
A web browser’s cache stores recently accessed versions of files obtained from the internet for use in displaying websites. Multimedia data such as photos, sound clips, and scripts written in HTML, CSS, and Java could be contained in these files.
Files can be cached for varying amounts of time, with defaults determined by how frequently certain types of files are accessed. To activate browser caching for WordPress, add the following code to 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>
- Enable Gzip Compression
Gzip is a highly effective compression method that can find duplicate text strings within a file and temporarily replace them, hence decreasing the file size. It’s a vital instrument for enhancing the rate at which web pages load.
Many hosting companies, including Cloudways, have Gzip compression enabled by default because of its widespread use at the server level. If you’re having trouble with .htaccess, you can add the following code to your WordPress.htaccess file or get in touch with your web host for assistance.
<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 have a noticeable impact on bandwidth utilization because any time an external resource requests an image, your server bandwidth is used to provide the image.
The following line of code can be added to the .htaccess file to stop bandwidth from being wasted on hotlinking images:
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)
WordPress Multisite uses a slightly modified version of the ordinary WordPress.htaccess file as its default.
- 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
The default .htaccess file for subdomain-based WordPress Multisite networks is:
# 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
Conclusion
When it is about server configuration, the WordPress .htaccess file is of utmost importance. This article will explain the significance of the .htaccess file.
I hope you found this guide helpful. Please leave your questions in the comments section below and I will surely answer them as soon as I see them.