The WordPress .htaccess File: The Complete Guide

print · Время на чтение: 18мин · - · Опубликовано · Обновлено

playListen to this article

The WordPress .htaccess File - The Ultimate Guide.htaccess file is a configuration file for WordPress websites hosted on the Apache HTTP web server. WordPress uses this file to control how Apache serves files from its root directory and its subdirectories. Specifically, WordPress modifies this file to be able to handle pretty permalinks on your site.

So, as you can imagine, the .htaccess file is an important part of your WordPress installation. If your web hosting provider uses Apache to host your website, then it will be created automatically when you install WordPress and for the most part you can forget about it. However, there may be situations where you have to fiddle with the .htaccess file. Examples include setting up 301 redirects after migration, forcing HTTPS on your website, and more.

In this article I will explain:

  • The purpose of the WordPress .htaccess file;
  • Where can you find the default WordPress .htaccess file location;
  • How to create .htaccess in WordPress if you don't already have one;
  • How to edit; and
  • How to use it to improve the security of your site.

which gives you a huge amount of control over your site's configuration. While you can use the file to increase the security of your site a bit, the biggest improvement will come when you install a modern WordPress security plugin. With great features such as daily automatic malware scans, one-click malware removal, robust built-in firewall, IP address blocking, real-time security alerts and more, the security plugin is the best solution for website security. WordPress.

The content of the article:

What is a WordPress .htaccess file?

As I mentioned earlier, the .htaccess file is a configuration file for WordPress websites hosted on the Apache HTTP web server. Apache handles any configuration changes through this per-directory file. What does it mean? Well, any directory and its subdirectories can be configured by creating a separate .htaccess file for it. So, if you want to customize something for your entire site, you will need to set the configurations in the .htaccess file in the root directory. If it doesn't exist, you'll have to create it first.

The default WordPress .htaccess file contains the following code:

# BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !- d RewriteRule . /index.php [L] # END WordPress

In particular, you can use the .htaccess file to manage and configure the Apache web server hosting your site. Think of Apache as one huge server hosting hundreds of thousands of sites, including yours, in so-called "server farms". Web hosting providers such as Bluehost and WP Engine have access to set up and run these server farms. Almost all web hosting providers let you create an .htaccess file so you can customize your site to suit your needs. If there were no .htaccess file, every site owner on the same server would have to use the same settings for their site, and you wouldn't have a say in what those settings should be for your site.

Here is a list of what you can do with the .htaccess file:

  • Set up 301 redirects after the migration.
  • Enforce HTTPS on your site.
  • Block IP addresses.
  • Deny access to certain files.
  • Send custom HTTP responses to specific requests.
  • Prevent hotlinking.

Next, let's see where this powerful file is located.

How to find the location of the .htaccess file on a WordPress site

By default, the .htaccess file is located in the root directory of your WordPress site. The root directory is usually the public_html directory, but may differ depending on your web host. You can access the root directory through the file manager in your hosting account's control panel, FTP or SSH. In this article, I will show you how to find the location of the .htaccess file in WordPress via cPanel and FTP (FileZilla).

Find .htaccess file in WordPress via cPanel

cPanel is a control panel that many web hosts have. This is probably the most popular control panel software among web hosts, but you can use other software like Plesk or Webmin. I'll be using cPanel for this section, but the steps should be basically the same for whatever control panel software your web host uses.

  1. Login to your hosting account and open file manager.
  2. File manager in cPanelYou need to enable cPanel to show hidden files. Open "Settings» in the upper right corner of the window. Then check the box next to "Show hidden files (dotfiles)" if it is not already installed and save the changes.Open Settings. enable the Show hidden files checkbox.
  3. In the navigation menu on the left, click on the root directory (in this case, public_html) to view its contents.public_html folder in navigation menu.

You should now see the standard WordPress .htaccess file.
WordPress .htaccess file.

Find the location of the WordPress .htaccess file via FTP

I will be using the FileZilla FTP client to show that you can find the default WordPress .htaccess file.

  1. Connect to your site in FileZilla using the appropriate FTP credentials. You can get them from your web hosting account.fast connection via FTP to the server
  2. To enable the display of hidden files in FileZilla, click on the "Server" menu and select the "Force show hidden files" checkbox.select "force show hidden files"
  3. Enter the root directory on the right side of the window called "Remote Site". You should see a .htaccess file inside this directory..htaccess file in the site's root folder

Please note that not all WordPress websites have the file .htaccess. If you don't see it in your root directory, it probably doesn't exist at all. The main reason for this could be that your site is not hosted on Apache. If your website is hosted on an Apache alternative like Nginx, then it will have a different configuration file. If this is your case, then this article is of no value to you.

How to create a file .htaccess in WordPress (3 ways)

The biggest reason to create a WordPress .htaccess file is because you don't have one. Other reasons for creating it include:

  • Your site is broken and you need to fix your WordPress installation.
  • The plugin has corrupted the .htaccess file, so you want to remove it and create from scratch.

Before making any changes to your website, it's a good idea to make a backup. If something goes wrong, you can restore a working version of your site. A backup is essentially an airbag for your website.

Create an .htaccess file using the WordPress admin panel

This method is the easiest way to get the .htaccess file for your WordPress site. All you have to do is go to "Settings»> «Permalinks» in the WordPress admin panel and click on «Save Changesat the bottom without changing anything. WordPress will now generate an .htaccess file for you.

If WordPress was unable to generate the .htaccess file, or you don't have access to the WordPress dashboard, read on to learn how to create .htaccess in other ways.

Create an .htaccess file using your hosting account's control panel

In this section, I will use cPanel to illustrate the process.

  1. Login to cPanel and open file manager.file manager in cPanel - shortcut.
  2. Enter the root directory from the left navigation menu.enter the public_html root folder on the server.
  3. Click the buttonFile» on the toolbar at the top of the user interface to create a new file.select the file button in the top left corner
  4. Name the file ".htaccess" and press "Create new file' to create it.create a new filename with .htaccess
  5. Right click and then click "Change" to edit the newly created .htaccess file.edit the generated .htaccess file
  6. Copy and paste the following lines of code into a file, and then save and close the file using the buttons in the top right corner of the user interface.
# BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !- d RewriteRule . /index.php [L] # END WordPress

If your site is multisite, add the following lines of code instead:

  • For subdirectory-based multisite, add the following:
# 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
  • For subdomain-based multisite, add the following instead:
# 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

Create the .htaccess file manually

If you want to create and upload a WordPress .htaccess file yourself, then the following steps are for you. You will need an FTP client so that you can upload the file to the root directory of your website. FileZilla is a good choice.

  1. Open the text editor of your choice.
  2. Copy and paste one of the following code snippets, depending on your website type:
  • For a basic WordPress site:
# BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !- d RewriteRule . /index.php [L] # END WordPress
  • For subdirectory based multisite:
# 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
  • For multisite based on subdomain:
# 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
  1. Name the file ".htaccess" and save it as a text file in a place where you can easily find it, then close it.
  2. Now connect to your site remotely via FileZilla using the FTP credentials obtained from your hosting account.
  3. Navigate to the folder where you saved the .htaccess file created in step 3 in FileZilla's "Local Site" section. Make sure the option to show hidden files is enabled.
  4. Upload the file to the root directory of your site. If the .htaccess file already exists, select the option to overwrite it when it appears. After the download is complete rename it to .htaccess.

You now have a brand new .htaccess file to customize your website to your liking. Now let's see how to edit an already existing .htaccess file in WordPress.

How to edit .htaccess file in WordPress

In most cases, you don't need to edit the .htaccess file in WordPress. However, if the need arises, you have quite a few ways to do it. Before I illustrate the steps, here are some tips to follow to minimize the chance of something going bad:

  • First, take a backup of your site. As I mentioned earlier, the .htaccess file is a critical file in your WordPress installation, so you definitely don't want your site to break accidentally. When it comes to backups, BlogVault is the best solution. It can back up sites up to 500GB in size, does incremental backups so as not to overwhelm server resources, and works with any web hosting provider. What's more, restoring backups with this plugin is as easy as clicking a button.
  • Use the staging site to test your changes first. A staging site is a copy of your live site where you can make and test changes without any risk. When you're happy with the changes, you can publish them to your live site.
  • Download the existing .htaccess file to your computer. He will act as a backup. That way, if your changes to the actual .htaccess file cause any problems, you can simply upload a backup copy of the file without having to restore the entire site.

Change .htaccess in WordPress with cPanel

  1. Login to cPanel with your hosting account and open File Manager.
  2. In the navigation menu on the left, click the root directory (in this case public_html) to open it.go to the root folder of the site
  3. From here locate the .htaccess file and right click to edit it.Click on the file - and select edit.
  4. Add the code before the line that says # END WordPress, making sure you don't break existing directives. Save and close the file.Add code to file.

Edit .htaccess in WordPress using a plugin

While using cPanel is fairly straightforward, using the plugin is even easier. The plugin I recommend for editing the WordPress .htaccess file is called Htaccess File Editor. The coolest thing about this plugin is that it backs up the .htaccess file every time you make changes to it. These backups can be restored later from the plugin itself or via FTP if you don't have access to the WordPress admin panel. It can also check the file for syntax errors.

  1. Install and activate the plugin Htaccess File Editor on your website.
  2. Go to "Settings» > «WP Htaccess Editor".WordPress .htaccess editor
  3. The plugin will warn you about the dangers of editing the .htaccess file. Scroll down to the red box, then click the button that says "I understand. Turn on the editor.Enabling the editor
  4. Add any code you want to the file, then click Save Changes. You can even check the file for syntactical correctness before saving it.

Edit WordPress .htaccess file using FTP client

If you don't want to add yet another plugin to your site, you can edit the WordPress .htaccess file manually. Here's how:

  1. Connect to your WordPress site in FileZilla.
  2. Navigate to the root directory from the right area labeled "Remote Site".
  3. Right click on the .htaccess file and select "View/Edit' to edit the file.Viewing/editing a file
  4. The file will open in the default text editor on your operating system. Add code or make changes to suit your needs, then save and close the file.
  5. FileZilla will tell you that the file has changed and ask if you want to upload the updated file back to the web server. Select "Yes" to do so.updated file

That's all! Ready.

How can I use an .htaccess file to secure WordPress?

I've said it before and I'll say it again: the WordPress .htaccess file is a very powerful file that gives you a huge amount of control over how your site behaves. One important use of the file is to increase the security of your website. In this section, I will show you some examples.

Force HTTPS on your site via htaccess

To force HTTPS on your website, you will first need an SSL certificate for your website. Once you have it, you can add the following lines of code to your .htaccess file:

# require SSL SSLOptions +StrictRequire SSLRequireSSL SSLRequire %{HTTP_HOST} eq "yourwebsite.com" ErrorDocument 403 https://yourwebsite.com # require SSL without mod_ssl RewriteCond %{HTTPS} !=on [NC] RewriteRule ^.*$ https: //%{SERVER_NAME}%{REQUEST_URI} [R,L]

Replace "yourwebsite.com" with the actual domain name of your site.

Deny access to confidential files

To prevent anyone from accessing a specific file, add the following piece of code to your .htaccess file, replacing "secretfile.ext" with the name and extension of the file you want to protect:

# prevent access to a specific file Order allow,deny Deny from all

To password protect different types of files and not just one specific file using the htpasswd utility, add the following code snippet (the extensions must be enclosed in parentheses; I've provided a few examples):

Order Allow,Deny Deny from all

Restrict access by IP address

To prevent access to your site from a specific IP address or domain, add the following code snippet. In this example, all IP addresses are allowed access except 12.135.57.870 and example.com:

# allow all except those indicated here Order allow,deny Allow from all Deny from 12.135.57.870 Deny from example\.com

HTTP security headers

I support and manage several sites of various kinds and what I saw. No site uses HTTP security headers. The presence of such headings on the site is an elementary degree of protection. And also, this is a way to maximize the authority of the site in the eyes of search engines in terms of security. I think you will benefit from this.

Security headers are easy to overlook when auditing a website. While some might say that website security is not SEO related, it becomes SEO related when a site is hacked and search traffic drops to zero. Security headers should be the top concern of anyone who posts anything on the web.

The good news is that they are relatively easy to set up and will help keep your site and your visitors safe.

This is how a site that does not have the necessary HTTP security headers looks like you can check your site at securityheaders.com:

site not having the necessary HTTP security headers

How to add HTTP security headers to your site?

Adding HTTP security headers is also done by editing the .htaccess file. You should add the following code to this file - be sure to enclose the specified lines in parentheses, as shown below:

# Security Headers Header always set Strict-Transport-Security: "max-age=31536000" env=HTTPS Header always set Content-Security-Policy "upgrade-insecure-requests" Header always set X-Content-Type-Options "nosniff" Header always set X-XSS-Protection "1; mode=block" Header always set Expect-CT "max-age=7776000, enforce" Header always set Referrer-Policy: "no-referrer-when-downgrade" Header always set X -Frame-Options SAMEORIGIN Header always set Age "216000" Header always set X-Permitted-Cross-Domain-Policies "none" Header always set unset X-Powered-By Header always set unset server Header always set Permissions-Policy "accelerometer= Origin(), autoplay=(), camera=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), publickey-credentials-get=(), usb=()" Header unset X-Powered-By Header unset server Header append Vary "Accept-Encoding, User-Agent, Referer" ## Caching rules # Don't cache by default Header set Cache-Control no-cache Header set Expires: 0 # Cache static assets for 1 day Header set Cache-Control "max-age=86400, public" # End of security headers

Please note: the code has been tested and works correctly on all sites in which it was implemented. I have compiled the complete code with all the necessary (basic) HTTP security headers.

HTTP Security Headers - Result Decryption

After injecting the code to set the required HTTP security headers, you will receive the following during verification:

This is what a site looks like with the necessary HTTP security headers

  • server is a server header, apparently advertising the software running on the server, but you can remove or change this value.
  • Content Security Policy is an effective measure to protect your site from XSS attacks. By whitelisting sources of allowed content, you can prevent the browser from loading malicious resources. Analyze this policy in more detail. You can register a free account on a report URI to collect problem reports on your site.
  • X-Frame-Options tells the browser whether you want to allow your site to be framed or not. By preventing browser framing of your site, you can protect yourself from attacks such as clickjacking.
  • HTTP Strict Transport Security is a great feature to support on your site that hardens the implementation of TLS by forcing the user agent to use HTTPS.
  • X-Content-Type-Options stops the browser's attempts to MIME-sniff the content type and forces it to stick to the declared content type. The only valid value for this header is "X-Content-Type-Options: nosniff".
  • X-XSS-Protection sets the configuration for the XSS Auditor built into older browsers. The recommended value was "X-XSS-Protection: 1; mode=block", but now you should look at the Content Security Policy instead.
  • Expect-CT will soon become obsolete and may be removed.
  • Referrer-policy (Referrer policy) is a new header that allows a site to control the amount of information the browser includes when navigating away from a document and should be set on all sites.
  • Permissions-policy (permission policy) is a new header that allows the site to control which features and APIs can be used in the browser.

Deciphering the test results

While these code snippets may slightly increase your site's security, the biggest improvement in your site's security will come from installing a proper security solution. With features such as daily automatic malware scans, one-click malware removal, a state-of-the-art integrated firewall, IP address blocking, real-time security alerts, and more, the security plugin is the best solution for securing WordPress websites. .

Conclusion

The WordPress .htaccess file is a very powerful and important part of your website. It allows you to customize your website to the smallest extent. The three main ways to create or edit an .htaccess file in WordPress are through your hosting account's file manager, FTP, or a plugin.

Among other things, one way to use the .htaccess file is to increase the security of your site. However, it is not a replacement for a dedicated security solution. One of the best solutions for this job is a security plugin. It will scan your website for malware on a daily basis, it comes with a modern firewall, and it will also alert you to any suspicious things in real time.

FAQ

What is an .htaccess file in WordPress?

The WordPress .htaccess file is a configuration file for websites hosted on the Apache HTTP web server. WordPress uses this file to control how Apache serves files from its root directory and its subdirectories, in addition to managing redirects and permalinks. You can also use this file for a wide variety of purposes such as blocking access to your website for certain IP addresses or address ranges, password protection of files and directories, enforcement of HTTPS, and more.

My .htaccess file is missing. How can I create it?

You can create an .htaccess file in WordPress by visiting Settings > Permalinks in the WordPress admin panel and clicking Save Changes at the bottom without changing anything. If that doesn't work, you can either create one using your hosting account's control panel, or create a local file and then upload it to your root directory via FTP.

How can I edit the .htaccess file?

You can edit the .htaccess file using your hosting account's control panel, with a plugin like Htaccess File Editor, or via FTP.

Reading this article:

Thanks for reading: SEO HELPER | NICOLA.TOP

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 190

No votes so far! Be the first to rate this post.

Читайте также:

3 Responses

  1. Александр says:

    Hello.
    Please tell me what this sign means:
    Header append Vary “Accept-Encoding, User-Agent, Referer”
    User-Agent - this is understandable - this means that the html css on the site changes depending on the user agent (for example, for mobile and desktop versions of the page, the content will be different).
    What does this entire code mean – Accept-Encoding, User-Agent, Referer
    Thank you in advance for your response!

    • Николай Алексеев says:

      Hello, I apologize for the long response. I am in the process of transferring this site to a new domain. Regarding your question: this is a selection of a group with many headers used: Accept-Language, Accept-Encoding, User-Agent, Referer

  2. Humberto says:

    It's not my first time to pay a quick visit this web page, i
    am browsing this website daily and get pleasant data from here daily.

Добавить комментарий

Your email address will not be published. Обязательные поля помечены *

five × 5 =