Monday, 05-12-2022

WordPress .htaccess File: How to Use and Edit It

5/5 - (1 vote)

htaccess is a special file that only works on Apache servers. WordPress also uses the .htaccess file to rewrite links when configuring Permalink. This article will provide you with code samples that can be used in .htaccess files for many different purposes for your WordPress website such as redirecting paths, security, blocking IPs, anti-comment spam…

Table of Contents

What is a htaccess file

htaccess files, also known as “distributed config files”, allow you to make configuration changes per directory. One or more configuration directives are placed in a specific document directory. The directives will apply to all subdirectories and that particular directory.

Apache uses .htaccess to handle configuration changes per directory.

The Apache Access Configuration file extension HTACCESS is a file with the HTACCESS extension. It stands for “hypertext access” These files are used to invoke an exception from the global settings which apply to all directories in an Apache website.

The global settings will be overridden if the file is placed in one directory. You can create HTACCESS files to redirect a URL, prevent directory listing, ban specific IP addresses, prevent hotlinking, etc.

This file can also be used to point to an htpasswd directory that stores credentials that prevent visitors from accessing the particular directory.

The .htaccess (hypertext access) file is a file located in the root directory of the hosting and managed and authorized by apache. The .htaccess file can control, configure many things with a variety of parameters, it can change the default set values of apache.

If exploited well, .htaccess will help you a lot with very little effort, just a few lines of command. The way you use the .htaccess file is also very simple, just open it with an editor, edit it, and save it as a .htaccess file.

Where is.htaccess file

Your WordPress root directory contains the WordPress .htaccess file. The root directory could be labeled with a number of different names depending on the hosting provider. It can be found using File Manager within your hosting account’s control panel.

htaccess file location

The .htaccess file is usually found in the root directory (usually public_html, www, htdocs …) and is on par with the robots.txt file. However, there are special cases where it is located outside the root directory of the website and affects all directories and websites located in that user.

You can find the .htaccess file in the following way:

  • For DirectAdmin host, you can go to File > select public_html > .htaccess
  • For Cpanel host, select File Manager > select public_html > .htaccess

Note that some hosts will hide the .htaccess file. You must select “show hidden files” mode to see the .htaccess file

Why You Can’t Find .htaccess File

There are 3 cases where you cannot find the .htaccess file.
Case 1: The .htaccess file has not been created.

Normally, WordPress will automatically create the htaccess file when you enable the Permalinks function. However, when you have not enabled this function, it will not create and you can create an htaccess file by going to WordPress Dashboard >> Settings >> Permalinks and then choosing one of 5 options:

  • Custom Structure,
  • Post name,
  • numeric, Month, and name,
  • Day and name

then click Save

Case 2: The .htaccess file has been hidden

 

Common uses for .htaccess files

There are many uses for the .htaccess files. These are the most popular examples:

  • Redirections to certain URLs
  • Load custom error pages, like 404 pages
  • Forcing your website to use HTTPS over HTTP
  • Allow or deny access to specific IP addresses on your website
  • Password-protect specific directories on your server

These are just a few examples. This is the most requested section on this page. This section is frequently updated.

301 redirect htaccess

A 301 Permanent redirect permanently redirects one URL from another. To send visitors to a different URL, you can use .htaccess. This will tell search engines that a page moved to allow them to properly index the page.

A 301 redirect with the .htaccess is a common use:

  • You can redirect visitors to your new site by using a 301 redirect from the old domain after you move to a new domain.
  • You can use 301 redirects for users to go to new pages after moving pages from an old site to a new structure.
  • You can use 301 redirects after combining two websites to make sure visitors go to the new pages.

To create and manage redirects on HostPapa websites, you can use.htaccess file. You can either create a.htaccess files using File Manager in cPanel or upload a.htaccessfile you have created using a text editor on your own computer using FTP.

Note: The .htaccess files are hidden files so you will need to set up the cPanel File Manager and an FTP client to view hidden files on your computer. You can find out how to do this by following the steps below.

Developer tip To restore functionality to a site after adding or updating .htaccess files, rename or delete the file.

Redirecting a single URL

This code can be used to redirect a single URL. Make sure to substitute “old page”, for “new page”, in your page names. ):

Redirecting a single folder

The following steps can be used to redirect a folder to a different location:

For examples, we used “folder” & “location”. Substitute folder and location names

Redirecting old URLs to new URLs

You can change the filenames of specific pages by entering the following code. Replace “oldpage”, “example” and “newpage” with your information:

Redirecting www to Non-www using a 301 .htaccess redirect

You might want to create a redirect to avoid using a subdomain of www. If that is the case, then you will need to redirect to a version other than www. This is what you will need: Simply replace “example.” with your domain.

Redirecting Domain Names

Use the following code to redirect an entire domain to another domain:

WordPress htaccess

This file is used by WordPress to control how Apache serves files from its root and subdirectories. WP modifies the file in order to allow for pretty permalinks.

This page can be used to repair a corrupted .htaccess file (e.g. A misbehaving plugin).

The .htaccess is either in the root directory of your webpage or in the directory you want to protect. If you are using Cpanel, htaccess file location is found in your website’s public_html folder (/home/username/public_html).
Because htaccess is a system configuration file and starts with a dot (.htaccess), so in some cases, you can’t see the file but you have to turn on showing hidden files to see it. That’s Why sometimes you Can’t Find the .htaccess file on your WordPress site.

For other FTP clients, you will find the option to show hidden files in-app settings or preferences menu.

After enabling this option, you would be able to view all hidden files including the .htaccess file. In case you can’t find it, maybe it doesn’t exist. You can create it manually or by saving the setting in Permalink in WordPress Settings » Permalinks page.

Common Uses of .htaccess File

There are several use cases for the .htaccess file. The most common examples include:

  • Add redirections for certain URLs or folders
  • Change default server error pages, like 500 pages, 501 pages, 404 pages,…
  • Force your site to use HTTPS instead of HTTP
  • Password-protect certain directories on your server
  • Prevent hotlinking

Using .htaccess files is a powerful tool for managing your server, but it can be tricky. Make sure you are familiar with making changes to your server before you start editing .htaccess files.

Please note that the default WordPress htaccess file only contains the following code, other code you found in your .htaccess file may be added by other plugins or server configurations.

If you want to add other code to your .htaccess file, please ADD IT OUTSIDE of the above code snippet. Otherwise, it may lose when you update the WordPress setting.
For example:

Wrong:

The Right Way to Add to .htaccess in WordPress CMS:

How to locate and edit the .htaccess file in WordPress

The .htaccess file is usually hidden. WordPress hides the .htaccess file because it is very important and can be accidentally deleted.

To locate the .htaccess file, log in to your WordPress hosting account. Next, navigate to the Cpanel. Launch the File Manager, then choose the Public_html folder.

You will need to make the .htaccess file visible. To do this, select Setting. This is usually located in the right-hand corner on the cPanel Folder Manager. A window will appear once you have selected Settings. Select the option Show hidden files.

Go back to the public_html folder. The .htaccess should now be visible.

Editing the .htaccess file can be done in many ways. We will show you all in the following paragraphs.

  1. Edit htaccess WordPress File from cPanel
  2. Edit htaccess WordPress File using FTP Client
  3. Or Edit htaccess WordPress File with a Plugin

Backups

Take a complete backup before you make any changes to WordPress .htaccess files. It is important to keep the file safe and avoid accidentally deleting it. You may not see the desired modification on your site if you make changes to the .htaccess file.

It could even cause the site to be unusable. No matter what happens, you can restore your site quickly to its original state if you have a backup. It’s easy.
Let’s now show you how to edit your .htaccess file.

Editing .htaccess File from cPanel

First:

Log in to your hosting account. Next, navigate to Cpanel and choose File Manager.

2nd Step:

Go to the Public_html folder in the File Manager. This folder contains the .htaccess file. Right-click to locate it and choose Edit.

Right-click to select Edit

That’s it. You can now insert code snippets to modify your website.

Edit htaccess WordPress File using FTP Client

FTP clients are another way to edit the .htaccess files. FTP clients are a tool that connects your website and your computer. Filezilla is an FTP client that allows you to access your website’s files from any computer on your network. This is how an FTP client can edit the file .htaccess.

Step 1: First, install Filezilla
Download Filezilla and install it on your computer. This is the most popular FTP client. Open it once you have it installed.

Step 2 – Find Your FTP Credentials
You will need your FTP credentials to connect Filezilla with your website. It’s possible to ask your hosting provider, but you can also search for it yourself.

FTP credentials are made up of hostname and username, password, and port number.

Filezilla offers several options in the top window that allow you to insert your FTP credentials. After you’ve done this, click Quickconnect to connect the software to your website.
Insert your hostname, username, and password, as well as the port number.

Step 3: Locate and Edit the .htaccess file

Filezilla can be divided into two parts. The local section shows you a collection of files from your computer. The remote shows you a collection of files from your website.

Select public_html from the remote section. The Filename section, located below the Remote site section, will contain the contents of the folder.

Right-click on the .htaccess file and choose Edit.

Go to Remote site > Filename>.htaccess
Next, we will show you how to modify your .htaccess file with a plugin.

Editing .htaccess File with a Plugin

Editing the .htaccess files via cPanel or via FTP client can be a little risky as you need to access the site’s back up and then edit the file. It can be overwhelming for website owners to access WordPress files. It wouldn’t surprise you to find yourself in this situation. A plugin is a safer option.

Although there are many plugins available to edit .htaccess files, we decided on Htaccess Editor after careful consideration. This plugin has more than 50,000 active installations and has received over 20 5-star ratings. It’s also frequently updated, according to the repository page. Htaccess Editor meets all requirements for selecting the correct plugin.

To ensure compatibility, you should first stage your website before installing the plugin. Compatibility issues could cause problems such as misbehaving sites and the inability to use certain plugins.

After you have tested it, you can edit the .htaccess file using a plugin.

First:

Install and activate HTML Access Editor to your WordPress website.

2nd Step:

Next, navigate to Settings and then choose WP HTMLaccess Editor. This will take you directly to the .htaccess file. You can insert any code snippet, but you must save the changes.

Default WordPress htaccess

WordPress should create a.htaccess for you automatically – but sometimes it’s not able to due to file permissions issues. Follow the below steps if that happens.

Log in to your WordPress dashboard, and then go to \

.

Scroll to the bottom, and then click Save Changes.

WordPress will now attempt to create a.htaccess. file. WordPress will now attempt to generate a .htaccess file. If it fails, you’ll get an error message at the bottom saying “.htaccess files are not writeable”.

The .htaccess file must be manually created. Log in to the control panel of your hosting account.

Start the File Manager.

Click on the public_html folder in the navigation menu located on the lefthand-hand side of the screen.

Click the +File button in the toolbar near the top of the screen.

In the New File Name input box, type “.htaccess”.

Click on Create New File.

To edit the file, right-click it.

You can add one of these codes.

You can use Basic WordPress if you only have WordPress on 1 domain.

Basic WP

Multisite

WordPress 3.5 and up #WordPress 3.5 and up
If you activated Multisite on WordPress 3.5 or later, use one of these.

Subfolder Example

SubDomain Example

Save and close the file.
Now that you know how to create a default .htaccess file for your WordPress site if it doesn’t exist already, you’re ready to edit it. Let’s look at how below.

Some advanced htaccess code for your WordPress site

Here are some specific examples, this is the most popular section of this page. Updated frequently.

Redirect Everyone Except IP address to an alternate page

When developing sites

This lets google crawl the page, lets me access without a password, and lets my client access the page WITH a password. It also allows for XHTML and CSS validation! (w3.org)

Fix double-login prompt
Redirect non-HTTPS requests to HTTPS server and ensure that .htpasswd authorization can only be entered across HTTPS

Set Timezone of the Server (GMT)

Administrator Email for ErrorDocument

ServerSignature for ErrorDocument

Charset and Language headers

Disallow Script Execution

Deny Request Methods

Force “File Save As” Prompt

Show CGI Source Code

Serve all .pdf files on your site using .htaccess and mod_rewrite with the php script.

Rewrite to www

Rewrite to www dynamically

301 Redirect Old File

301 Redirect Entire Directory

Protecting your PHP.cgi

Set-Cookie based on Request
This code sends the Set-Cookie header to create a cookie on the client with the value of a matching item in 2nd parentheses.

Set-Cookie with env variable

Custom ErrorDocuments

Implementing a Caching Scheme with .htaccess

Password Protect single file

Password Protect multiple files

Send Custom Headers

Blocking based on User-Agent Header

Blocking with RewriteCond

.htaccess for mod_php

.htaccess for PHP as CGI

Shell wrapper for custom php.ini

Add values from HTTP Headers

Stop hotlinking

Other Example .htaccess Files

Here are some default MOD_REWRITE code examples.

Examples of protecting your files and securing with password protection.

Advanced Mod_Rewrites

Here are some specific htaccess examples taken mostly from my WordPress Password Protection plugin, which does a lot more than password protection as you will see from the following mod_rewrite examples.

These are a few of the mod_rewrite uses that BlogSecurity declared pushed the boundaries of Mod_Rewrite! Some of these snippets are quite exotic and unlike anything, you may have seen before, also only for those who understand them as they can kill a website pretty quick.

Directory Protection

Enable the DirectoryIndex Protection, preventing directory index listings and defaulting.

Password Protect wp-login.php

Requires a valid user/pass to access the login page

Password Protect wp-admin

Requires a valid user/pass to access any non-static (CSS, js, images) file in this directory.

Protect wp-content

Denies any Direct request for files ending in .php with a 403 Forbidden.. May break plugins/themes

Protect wp-includes

Denies any Direct request for files ending in .php with a 403 Forbidden.. May break plugins/themes

Common Exploits

Block common exploit requests with 403 Forbidden. These can help a lot, may break some plugins.

Stop Hotlinking

Denies any request for static files (images, CSS, etc) if the referrer is not a local site or empty.

Safe Request Methods

Denies any request not using GET, PROPFIND, POST,OPTIONS, PUT,HEAD

Forbid Proxies

Denies any POST Request using a Proxy Server. Can still access the site, but not comment.

Real wp-comments-post.php

Denies any POST attempt made to a non-existing wp-comments-post.php

HTTP PROTOCOL

Denies any badly formed HTTP PROTOCOL in the request, 0.9, 1.0, and 1.1 only

SPECIFY CHARACTERS

Denies any request for a url containing characters other than “a-zA-Z0-9.+/-?=&” – REALLY helps but may break your site depending on your links.

BAD Content Length

Denies any POST request that doesnt have a Content-Length Header

BAD Content-Type

Denies any POST request with a content type other than application/x-www-form-urlencoded|multipart/form-data

Missing HTTP_HOST

Denies requests that don’t contain an HTTP Host Header.

Bogus Graphics Exploit

Denies obvious exploit using bogus graphics

No UserAgent, Not POST

Denies POST requests by blank user-agents. May prevent a small number of visitors from POSTING.

No Referer, No Comment

Denies any comment attempt with a blank HTTP_REFERER field, highly indicative of spam. May prevent some visitors from POSTING.

Trackback Spam

Denies obvious trackback spam.

Map all URIs except those corresponding to existing files to a handler

Map any request to a handler

In the case where all URIs should be sent to the same place (including potentially requests for static content) the method to use depends on the type of the handler. For php scripts, use: For other handlers such as php scripts, use:

And for CGI scripts:

Map URIs corresponding to existing files to a handler instead

If the existing files you wish to have handled by your script have a common set of file extensions distinct from that of the hander, you can bypass mod_rewrite and use instead mod_actions. Let’s say you want all .html and .tpl files to be dealt with by your script:

Deny access if var=val contains the string foo.

Removing the Query String

Adding to the Query String

Keep the existing query string using the Query String Append flag, but add var=val to the end.

Rewriting For Certain Query Strings

Rewrite URLs like http://google.com/url1?var=val to http://google.com/url2?var=val but don’t rewrite if val isn’t present.

Modifying the Query String

Change any single instance of val in the query string to other_val when accessing /path. Note that %1 and %2 are back-references to the matched part of the regular expression in the previous RewriteCond.

Disable browser caching for all files that don’t get a hash string by Angular.

Remove X-Powered-By header

Remove server signature

This is a fairly simple RewriteRule. Use the expression (-4)? to optionally match the -4 and redirect it to /blog-5 along with requests to /blog/. The second (.*) group after the / captures everything else into $2.

The above will do a silent internal rewrite. If you actually want to redirect and have the browser the new URL, change [L] to [L,R=301].

Note: Realizing blog-4 is probably a variable name, use (-.+)? to match anything. But you also need a RewriteCond so it doesn’t match blog-5:

Forcing Non-WWW with HTTPS Site Addresses

When you add this information to your .htaccess file, any visitors who type in www.huyhoa.net will be sent to huyhoa.net.

Replace huyhoa.net with your domain.

Forcing WWW with HTTPS Site Addresses with .htaccess

Remember to replace huyhoa.net with your domain.

Creating a Custom 404 Error Page with .htaccess

You can change any error page using the .htaccess file.
For example:

See all list of HTTP status codes here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Denying and Allowing Access

Deny except specific IPs

Allow except specific IPs

Set Expires

Temporary Maintenance using Mod_Rewrite

Prevent Image Hotlinking

Redirect a Single Page

Redirect Using RedirectMatch

Alias a Single Directory

Redirect an Entire Site

Exclude URL from Redirection
This snippet allows you to exclude a URL from redirection. For example, if you have redirection rules set up but want to exclude robots.txt so search engines can access that URL as expected.

RewriteEngine On
RewriteRule ^robots.txt[L]

Deny Access to Hidden Files and Directories

Hidden files and directories (those whose names start with a dot .) should most, if not all, of the time, be secured. For example: .htaccess, .htpasswd, .git, .hg…

Alternatively, you can just raise a “Not Found” error, giving the attacker no clue:

Deny Access to Backup and Source Files

These files may be left by some text/HTML editors (like Vi/Vim) and pose a great security danger if exposed to the public.

Disable Directory Browsing

Performance

Compress Text Files

Set Expires Headers

Expires headers tell the browser whether they should request a specific file from the server or just grab it from the cache. It is advisable to set static content’s expires headers to something far in the future.

If you don’t control versioning with filename-based cache busting, consider lowering the cache time for resources like CSS and JS to something like 1 week. Source

Set PHP Variables

# For example:

 

References:

Share.
About Author

Leave A Reply