How to Protect, Optimize and Control Redirects in WordPress with .htaccess Files

.htaccess is an important core file in WordPress, usually used toAdd, modify, and override server-level configuration, security, and performance parameters.

Simply put, it makes website addresses more aesthetically pleasing, automatically redirects visitors to a new address, and improves website security by blocking unauthorized access.

In most cases, this can be done by updating or changing the WordPress .htaccess rules in the file to address server-level operational issues.

However, many website owners do not understand .htaccess file's true potential, and therefore missed opportunities to optimize the server (as well as the site).

To help WordPress users, this post will detail how to find and edit WordPress .htaccess documentation, and how the various rules are applied.

take note of: The rules and configurations mentioned below apply to Apache 2.4.

Image[1]-In-Depth Analysis of WordPress .htaccess File: The Ultimate Guide to Optimizing Website Performance and Security

What is WordPress .htaccess Documentation?

.htaccess Files can be thought of as the control center of the site, containing a set of rules that govern all communication between the WordPress site and the server.

This can be done in the WordPress Installation(used form a nominal expression)In the home directory, find the .htaccess file. WordPress uses this file by default to handle tasks such as redirect management and fixed link structure settings.

Specifically..htaccess file (also known as a server configuration file) can be used in WordPress for the following tasks:

  • Control access to website pages
  • Improve website security and performance

In addition, it is possible to place .htaccess file is placed in any folder on the site to change the behavior of that folder.

⚠️ Important Reminder!

.htaccess The file is very sensitive to modification, even by a single symbol (such as .) Putting it in the wrong place can cause the site to crash. Therefore, it is important to have a good understanding of the .htaccess Before making any changes to the file, be sure to backing up to a secure storage location.

How to use .htaccess in WordPress and take advantage of it?

To use the .htaccess file, you can follow the steps below:

1. Finding .htaccess file

.htaccess file is located in the root directory of your WordPress website. You can use the file manager maybe FTP client Go to the main folder of the site to find it. Be aware that the.htaccess The file may be hidden by default, and if you can't see it, you need to adjust the settings of your file manager so that it shows hidden files.

2. Adjustment of file manager settings

If the site's .htaccess The file is not visible, and you may need to modify the settings of your file manager so that it shows hidden files. This step ensures that you can smoothly access and modify .htaccess Documentation.

3. Creating backups

countering (a dispute) .htaccess Before making any changes to the file, be sure toBackup first.original document. In this way, even if problems arise during the modification process, you can always revert to the original state to avoid affecting the normal operation of the website.

The role and advantages of .htaccess files

This can be done by .htaccess files to optimize and protect WordPress websites, here are some common uses and their advantages:

functionalitydescriptive
Customized fixed link structureCreate user and search engine friendly URLs to improve SEO and accessibility.
Redirectsutilization 301 Redirect Make URL changes or content migrations to ensure a great user experience and maintain SEO rankings.
security enhancementRestrict access to sensitive areas, directories and files by adding rules to prevent unauthorized access.
protection against chain theftPrevent other websites from calling your resources directly, protect bandwidth, and ensure content is only accessible through your website.
Caching and compressionpass (a bill or inspection etc) .htaccess start usingbrowser cacherespond in singingGzip compression, speeding up page loading and improving the user experience.
Customizing the error pageCreate custom error pages (e.g. 404) to give users a better experience when they encounter errors.

How to find .htaccess files in WordPress?

Recommended by the WordPress community NGINX respond in singing Apache as the web server. If the WordPress site is running on NGINX server, will not see the .htaccess file because NGINX does not use it.

But if the WordPress site is placed in the Apache Web Server On the website, it can be found in the root directory(public_html maybe www folder) to find the .htaccess Documentation.

How do I access the .htaccess file?

You can use FTP client(e.g. FileZilla) to connect to the server and go to the root directory of the WordPress site to access the .htaccess file. For example, the path to the root directory of a particular website might be:/applications/sqzucfcyqb/public_html

Image [2]-In-depth analysis of WordPress .htaccess files: the ultimate guide to optimizing site performance and security

What should I do if I can't find the .htaccess file?

If you don't see .htaccess file, probably because it ishidden file(no file extension), which is usually hidden by default by the file manager for security reasons.

To access .htaccess file, you have to add the file to an FTP client (such as the FileZilla(used for emphasis)Server OptionsIn the "Force Showing Hidden Files"Like this. .htaccess The file is then displayed.

Image [3]-In-Depth Analysis of WordPress .htaccess File: The Ultimate Guide to Optimizing Your Site's Performance and Security

WordPress default .htaccess file

default .htaccess file is located in the WordPress installation's root directoryThe usualhiddenbut can be accessed through an FTP client such as FileZilla) Access.

What should I do if I can't find the .htaccess file?

If you still can't find it in the root directory .htaccess file, you canManually createdA new .htaccess Documentation:

  • expense or outlay laptop computer(or other text editor) to create a blank file.
  • Name the file ".htaccess"(Make sure the filename starts with . beginning).
  • When saving, select "Document type" because of "All Files"., and then save it to your desktop.
    Image [4]-In-Depth Analysis of WordPress .htaccess File: The Ultimate Guide to Optimizing Your Site's Performance and Security
    • Using an FTP client (e.g. FileZilla) to send the .htaccess file to the WordPress installation's root directoryThe

      ⚠️ take note of
      The filename must be ".htaccess"Instead of "htaccess"(must have . (No.).

      WordPress default .htaccess file content

      WordPress Default .htaccess The contents of the document are as follows:

      # BEGIN WordPress
      
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.php$ - [L]
      RewriteCond %{REQUEST_FILENAME} ! -f
      RewriteCond %{REQUEST_FILENAME} ! -f RewriteCond %{REQUEST_FILENAME} !
      RewriteRule . /index.php [L]
      </IfModule
      # END WordPress

      this one .htaccess The main role of documentation is to manage WordPress Fixed LinksTo ensure that all URL structures work correctly.

      How to create .htaccess file?

      It can be created in WordPress by following these steps .htaccess Documentation:

      1. go into WordPress DashboardThe
      2. strike (on the keyboard) Settings > PermalinksThe
      3. strike (on the keyboard) Save Changes Button.
      Image [5]-In-depth analysis of the WordPress .htaccess file: the ultimate guide to optimizing your website's performance and security

      Once you've done that, WordPress will add a new file to theroot directoryThe defaults are automatically generated under the .htaccess Documentation.

      default .htaccess file is only used to manage WordPress Permanent link. However, you can manually modify the file to add additional rules to control the Apache Web Server How to handle website related requests and actions.

      How to edit .htaccess file in WordPress?

      To edit the WordPress .htaccess file, which can be accessed with the file manager(provided by the WordPress host) or FTP client(e.g. FileZilla).

      How to edit .htaccess file

      • Connecting to the server using an FTP client (such as FileZilla)The
      • Go to the WordPress root directory(usually public_html folder), find the .htaccess Documentation.
      Image [6]-In-depth analysis of WordPress .htaccess file: the ultimate guide to optimizing website performance and security
      • right click .htaccess fileSelection "View/Edit.", open it with your favorite text editor.
      Image [7]-In-depth analysis of WordPress .htaccess file: the ultimate guide to optimizing website performance and security
      • Make the required changesAnd thenSave fileThe

        Another way to edit

        as wellfirstly .htaccess File download to local, which is modified on the computer and then passed through the FTP client maybe file manager Upload the modified file to replace the server's .htaccess Documentation.

        How to edit WordPress .htaccess file using cPanel?

        If you do not want to use the FTP method, you can choose cPanel to edit WordPress .htaccess Documentation. Here are the exact steps:

        Accessing the control panel (cPanel)
        Log in to your hosting account and go to Control PanelThe

        Open File Manager
        Find and open in the Control Panel "File Manager." Tools.

        go into public_html catalogs
        In the left navigation menu, click public_html file (paper)This is the main directory of the site.

        Image [8]-In-Depth Analysis of WordPress .htaccess File: The Ultimate Guide to Optimizing Your Site's Performance and Security

        Find the WordPress directory
        exist public_html directory, find and open the WordPress site folders(usually located directly in the public_html (Inside).

        Finding .htaccess files
        exist WordPress Catalog Inside, you'll see .htaccess Documentation.right click .htaccess file, select EditThe

        Modify the .htaccess file
        option Edit option, the browser will open atext editorThe

        Add Code
        exist .htaccess Documentation.Place the code to be added in the # BEGIN WordPress beforehand, and then save the changes.

          Follow the steps above to successfully use the cPanel to modify WordPress .htaccess fileThis optimizes the functionality and security of the website.

          How to edit WordPress .htaccess file using plugin?

          A different kind of editor .htaccess file by using the WordPress Plugine.g. Htaccess File Editor. These plug-ins allow you to add a new plug-in directly to the WordPress Backend compiler .htaccess files without having to use FTP or cPanel.

          Ways to edit .htaccess file with Htaccess File Editor plugin

          • Login to WordPress AdminThe
          • Search in the Plugin Library"Htaccess File Editor"plug-in (software component)The
          Image [9]-In-Depth Analysis of WordPress .htaccess File: The Ultimate Guide to Optimizing Your Site's Performance and Security
          • Install and activate the pluginThe
          • Go to "Settings" > "WP Htaccess Editor".The
          • exist .htaccess documentation # BEGIN WordPress Insert a new line of code before(can be used to add rules or configurations).

            Once you have completed the above, you canEdit directly in the WordPress backend .htaccess file, add the required code snippets to define the rules or configuration of the site.

            WordPress .htaccess redirection

            It is possible to use .htaccess file to manage the WordPress site'sredirects. Here are some common .htaccess Rules that can be used to set up and control redirects to a website.

            301 (permanent) redirect

            301 Redirect Telling search engines that a URL has been permanently moved to a new address is not limited to URLs, but can also be used to redirect folders, pages, or entire websites.

            Example: Place the oldpage.html redirect to newpage.html

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

            302 (temporary) redirection

            302 Redirection Indicates a temporary page move that does not affect SEO ranking changes.

            Example:

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

            Forcing URLs to use www

            the following .htaccess The rule forces all access to the example.com of the user jumps to the www.example.comThe

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

            Force URLs to use non-ww

            The following rule forces all access to the www.example.com of the user jumps to the example.comThe

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

            Force HTTPS

            The following rule forces all visitors to use HTTPS instead of HTTP.

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

            Force HTTP

            If you want to force all visitors to use HTTP instead of HTTPS, you can use the following rule:

            apacheCopyEditRewriteEngine On
            RewriteCond %{HTTPS} on
            RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
            

            Redirecting the root domain to a subdirectory

            The following rule will set the primary domain example.com Redirects to the specified subdirectory.

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

            Redirect a URL

            If there are two domains pointing to the same website, you can use the following rule to redirect one domain to the other:

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

            Redirecting individual posts or pages

            If you want to redirect a specific post or page, you can add the following code:

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

            Example:
            If you want to put https://www.cloudways.com/blog/core-web-vitals/ redirect to https://www.cloudways.com/blog/core-web-vitals-seo/, the following code can be used:

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

            Redirect the entire website to the new domain

            If you want to redirect your entire website to the new domain, you can use the following rules:

            apacheCopyEditRewriteEngine on
            RewriteCond %{HTTP_HOST} ^olddummydomain.com [NC,OR]
            RewriteCond %{HTTP_HOST} ^www.olddummydomain.com [NC]
            RewriteRule ^(. *)$ https://newdummydomain.com/$1 [L,R=301,NC]
            

            Example:
            If the old site was www.oldwebsite.com/about, after applying this rule, all accesses to the www.oldwebsite.com/about users are redirected to the www.newwebsite.com/aboutThe

            WordPress .htaccess securitydraw attention to sth.

            Since WordPress isopen source platformThe company is susceptible tosecurity holeThe impact of the Therefore, users must takeproactive measuresto protect the site, such as choosing a reliableserver providerPreventingMalicious Traffic and DDoS AttacksThe

            In addition, the .htaccess files to protect WordPress directories and files. Here are some of the .htaccess Security rules that can help improve the security of your WordPress site.

            Protecting .htaccess files

            .htaccess file can control the entire site, so it is necessary to preventUnauthorized access. The following rule can be used:

            apacheCopyEditorder allow,deny
            deny from all
            satisfy all
            </files
            

            Restricting access to the WordPress backend (wp-admin)

            If a hacker gets WordPress Backend access, they have full control over the website. Therefore, administrators can restrict Specific IP address in order to access the backend.

            1. Create a new .htaccess file, and paste the following code:
            apacheCopyEdit# Restrict wp-admin access (only specified IPs allowed)
            <Limit GET POST PUT
            order deny,allow
            deny from all
            allow from xx.xx.xx.xx
            # Allow specific IP addresses (replace xx.xx.xx.xx)
            
            1. Upload this file to /wp-admin/ catalogsThe
            2. If there are multiple administratorsYou can add more than one IP address:
            apacheCopyEditallow from 34.56.78.90 98.76.54.32 19.82.73.64
            

            Protect important documents (such as wp-config.php)

            wp-config.php The file stores the WordPress database credentialset al. (and other authors)sensitive informationRequiredProhibition of unauthorized accessThe

            apacheCopyEditorder allow,deny
            deny from all
            </files
            

            safeguard wp-content catalogs

            wp-content The catalog contains Themes, plugins, media files, is a major target for hackers. This can be achieved by .htaccess Restricted access:

            1. exist wp-content directoryCreate a new .htaccess Documentation.
            2. Add the following code, only allows access to specific file types (XML, CSS, JPG, PNG, GIF, JS):
            apacheCopyEditOrder deny,allow
            Deny from all
            
            Allow from all
            </Files
            

            Restricting access to internal WordPress files

            Some WordPress system fileshould not be accessible to regular users. It is possible to use the .htaccess Limitations:

            apacheCopyEditRewriteEngine 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

            Certain directories (e.g. /wp-includes/ respond in singing /wp-content/uploads/) is writable by default, which could be exploited by hackers. It is possible toDisable PHP execution, preventing malicious code from running.

            1. In the directory where you want to disable PHP execution(e.g. uploads directory) to create the .htaccess Documentation.
            2. Add the following code::
            apacheCopyEditdeny from all
            

            Restricting File Access for WordPress Plugins and Themes

            To prevent hackers from directly modifying thePlugins and ThemesPHP files, you can use the following .htaccess Rules:

            apacheCopyEditRewriteCond %{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]
            

            Preventing Script Injection Attacks

            Script Injection (SI) is a type ofhacking techniqueIt allows an attacker toInjecting malicious code into website code, used to steal data or hijack websites.
            You can use the .htaccess let's face it.Preventing script injection::

            apacheCopyEditOptions +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 access to a website from a specific IP address

            If someonemalicious attack (e.g. on a cell phone)websites (such as spam or hacking), can beBlock this IP address, denied access.

            1. exist .htaccess Add the following code to the file::
            apacheCopyEditorder allow,deny
            deny from 456.78.9
            allow from all
            </Limit
            
            1. When a blocked IP tries to access the siteThey'll see.403 Forbidden errorThe
            Image [10]-In-Depth Analysis of WordPress .htaccess File: The Ultimate Guide to Optimizing Your Site's Performance and Security

            Restricting access to specific files

            If you want to prevent a user from accessing a specific file (such as the your-file-name.txt), the following can be used .htaccess Rules:

            apacheCopyEditorder allow,deny
            deny from all
            </files
            

            Disable directory browsing

            By default, some servers allowDirectly browse the website catalogThis mayLeakage of sensitive documents, increasing security risks.
            You can do this by .htaccess prohibitedCatalog Listings, enhanced security:

            apacheCopyEdit# Disable directory browsing
            Options -Indexes
            

            By using the .htaccess documents that can be effectivelyImproving the Security of Your WordPress Website, preventing hacking, malicious access and data leakage. It is recommended to regularlybacking up .htaccess file, and carefully test before making changes to ensure that the site is functioning properly.

            summarize

            Regarding server configuration, the WordPress .htaccess file is one of the most critical files on the server. It is usually used to configure the server and protect various areas of the website.


            Contact Us
            Can't read the tutorial? Contact us for a free answer! Free help for personal, small business sites!
            Customer Service
            Customer Service
            Tel: 020-2206-9892
            QQ咨询:1025174874
            (iii) E-mail: info@361sale.com
            Working hours: Monday to Friday, 9:30-18:30, holidays off
            © Reprint statement
            This article was written by Banner1
            THE END
            If you like it, support it.
            kudos62 share (joys, benefits, privileges etc) with others
            commentaries sofa-buying

            Please log in to post a comment

              No comments