Http error 405 php

I'm getting a HTTP Error 405 when trying to post a small form using PHP. Codes are given below. How can I solve this one?
<form action="quiz.php"

I’m getting a HTTP Error 405 when trying to post a small form using PHP. Codes are given below. How can I solve this one?

  <div class="quiz-section">
            <form action="quiz.php" method="post">
                #################
            <input type="submit" class="btn blue" name="submitQuiz" value="Submit" />
        </form>
   </div>





<?php
    if (isset($_POST['submitQuiz'])) {
        if(isset($_POST['quest1'])&&isset($_POST['quest2'])&&isset($_POST['quest3']))
        {
            if(($_POST['guestName']!="")&&($_POST['guestEmail']!="")){

                $to      = 'a######@yahoo.com';
                $subject = 'Quiz Answer Submission';
                $message = "Submited by: ".$_POST['guestName']." From email: ".$_POST['guestEmail']." Answers are: ".$_POST['quest1'].", ".$_POST['quest2'].", ".$_POST['quest3'];

                $headers = 'From: j#####@live.in' . "rn" .
                    'Reply-To: '.$_POST["guestEmail"] . "rn" .
                    'X-Mailer: PHP/' . phpversion();

                mail($to, $subject, $message, $headers);
                echo "Thanks for your submission. We successfully received your answers. Stay tuned.";
                //header("Location: index.html#quiz-questions?status=Success");
            }
            else{
                    echo "Please go back and answer all quiz questions";
            }
        }
        else{
                echo "Please fill all the fields and answer to all questions";
                //header("Location: index.html#quiz-questions?status=Error");
        }
    }
?>

The Error message is:

The page cannot be displayed

The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.
Please try the following:

Contact the Web site administrator if you believe that this request should be allowed.
Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.
HTTP Error 405 - The HTTP verb used to access this page is not allowed.
Internet Information Services (IIS)

Technical Information (for support personnel)

Go to Microsoft Product Support Services and perform a title search for the words HTTP and 405.
Open IIS Help, which is accessible in IIS Manager (inetmgr), and search for topics titled Setting Application Mappings, Securing Your Site with Web Site Permissions, and About Custom Error Messages.

In this article, we will show you how to send a “405 Method Not Allowed” header using PHP.

The “405” status allows us to tell a client it is using an incorrect HTTP method.

This is an important header to have in your “toolbox” if you want to restrict certain PHP scripts to POST, PUT, or GET requests.

For example, let’s say that we want to restrict a PHP script to POST requests only.

//An array of HTTP methods that
//we want to allow.
$allowedMethods = array(
    'POST'
);

//The current request type.
$requestMethod = strtoupper($_SERVER['REQUEST_METHOD']);


//If the request method isn't in our
//list of allowed methods.
if(!in_array($requestMethod, $allowedMethods)){
    //Send a 405 Method Not Allowed header.
    header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
    //Halt the script's execution.
    exit;
}

//This will only be printed out if a
//POST request is used.
echo 'Hello world!';

In the PHP code above:

  1. We create an array of HTTP methods that we want to allow. In this case, we only want to allow POST requests. If we also want to allow PUT, HEAD and OPTIONS requests, then we can add them to the array as well.
  2. We retrieve the current request type by accessing the $_SERVER[‘REQUEST_METHOD’] variable.
  3. After that, we check to see if the current request type is in our array of allowed HTTP methods.
  4. If the current HTTP method is not present in our $allowedMethods array, we send a “405 Method Not Allowed” response to the client. We do this by using PHP’s header function.
  5. Finally, we terminate the script.

If you attempt to navigate to this PHP script in your browser, you will see the following:

405 error Chrome

“This page isn’t working.” An example of Chrome returning a 405 error.

This is because your browser sent a GET request to the page when the PHP script only accepts POST requests.

Furthermore, if you inspect the response headers for the request in your browser’s developer tools, you will see something like this:

405 Method Not Allowed

As you can see, our PHP script has returned a “405 Method Not Allowed” status code to the browser.

Using the http_response_code function to send a 405 error.

If you are using PHP version 5.4.0 or above, then you can use the http_response_code function.

This function is a little more concise:

//Send a 405 Method Not Allowed header using http_response_code.
http_response_code(405);
//Kill the script.
exit;

In the example above, we simply replaced the header function with the http_response_code function and passed in 405 as the $response_code parameter.

Related: Blocking POST requests with PHP.

Решение ошибки 405

В этом выпуске: признаки ошибки 405; решения проблемы ошибки 405 в PHP; советы по устранению Error 405. Подробно о проблеме и путях решения.

Появление ошибки 405 следует трактовать, как произведение операции сервером с запретом на определенном этапе ее совершения. Причин ее появления немало и нужно уметь определять ошибку на предмет признаков, хотя и в этом случае есть исключения.

Идентификация проблемы осуществляется с помощью диалогового окна с соответствующей информацией. После сообщения об ошибке, программа прекращает работу. В браузерах подобное известие может преследовать пользователя сразу на нескольких порталах. Чаще всего о признаках проблемы свидетельствует обозначения HTTP 405 и Method Not Allowed. Впрочем, в некоторых случаях владелец устройства не может сразу определить ошибку. К примеру, причин медленной работы операционной системы или слабого реагирования на действия с помощью клавиатуры и компьютерной мыши довольно много. На этом этапе нет отчетливых отличий 405-й ошибки от других сбоев.

Сюда же относятся периодические «зависания», когда компьютер перестает реагировать на любые действия пользователя и останавливает работу всех программ. В случае с отображением упомянутой ошибки в веб-обозревателях, то браузер может делать ложные выводы касательно определения проблемы. Например, нередко случаются ситуации, когда возникает ошибка 404 на нормально функционирующих ресурсах вместо 405. В свою очередь, делать вывод только по предупреждению от браузера не стоит.

Причины возникновения ошибки 405

Одним из самых распространенных источников проблемы является функционирование php-скрипта. Данный инструмент импортирует данные на сайт, но дело в том, что касательно выполнения скрипта существует временное ограничение в 30 секунд. Упомянутая опция устанавливается на хостинге и подобрать оптимальный для себя параметр невозможно. Исходя из этого, формируется и корень ошибки – скрипту недостаточно временных рамок, утвержденных хостингом. В результате этого пользователь может наблюдать ошибку 405. Если проблема возникает из-за приведенной причины, юзеру следует воспользоваться одним из советов.

Советы по решению ошибки 405 в PHP:

  • осуществление импорта базы данных с помощью одноименной опции, которую можно найти в подразделе Хостинг в Панели управления;
  • детализация файла путем формирования из него нескольких частей, после чего каждую из них передать через скрипт;
  • произведение импорта данных при помощи специального инструмента phpmyadmin;
  • создание cron-задачи с вводом пути к скрипту. Данная опция позволяет расширить временное ограничение в 10 раз, что в большинстве случаев вполне достаточно для импорта. Функция доступна в подразделе Хостинг, пункт Расписание задач (cron), а нужную информацию следует вводить в поле Задача.

Еще одной распространенной причиной ошибки часто становятся POST-запросы. Сущность проблемы заключается в обработке расширений файлов с помощью инструмента apache. Ряд расширений могут негативно влиять на работу скрипта, поэтому их следует удалить. Внести необходимые изменения нужно в окне Статические файлы. Путь к нему выглядит следующим образом: Хостинг – Мои сайты – Настройка сайта.

Как и во многих других ситуациях, вирусы могут быть причиной возникновения ошибки. Вредоносное программное обеспечение либо повреждает веб-обозреватель, либо полностью захватывает контроль над ним. В дальнейшем браузер может выдавать целый ряд известий о проблемах. Кроме того, удаление или установка системного программного обеспечения может привести к повреждению реестра, который, в свою очередь, инициирует ошибку 405.

Способы устранения: ошибка 405 (Error 405)

Для ликвидации проблемы рекомендуется принятие следующих мер:

  1. Восстановление записей реестра.
  2. Запуск сканирования устройство с целью проверки наличия вирусов и вредоносного программного обеспечения.
  3. Обновление драйверов.
  4. Применение опции Восстановление системы, чтобы аннулировать последние корректировки.
  5. Провести все требуемые системой обновления.
  6. Проверить системные файлы (sfc / scannow).
  7. Переустановить продукт WOS (Windows Operating System).
  8. Установить Windows заново.

Одна или несколько из перечисленных операций точно помогут пользователю избавиться от надоедливых уведомлений и запретов. Исходя из упомянутых рекомендаций, можно сделать вывод, что наиболее эффективная профилактика от появления подобных проблем – это поддержка операционной системы в надлежащем функционировании.

Дальше по теме…

Updated on January 6, 2023

How to fix 405 method not allowed error

405 Method Not Allowed Error WordPress

Table of Contents [TOC]

  • 405 Method Not Allowed Error WordPress
    • What is the Error 405 Method Not Allowed?
      • 405  Error In Microsoft Edge
      • 405  Error In Safari
      • 405  Error in Firefox
      • 405 Method Not Allowed Google Chrome
    • 405 Method Not Allowed Error Variations
    • What Causes Http Error 405 Not allowed?
    • Diagnosing the Error 405 Method Not Allowed Message
    • Fix or Resolve Error 405 Method Not Allowed?
      • Enable the 405 Method Not Allowed Http Post
      • Input Correct Url to Avoid Http Status 405 Method Not Allowed
      • Roll Back WordPress Updates – Status Code 405 Method Not Allowed
      • Uninstall New Extensions, Modules, Plugins and Themes
      • Check if Unexpected Database Changes Causing Error 405 Method Not Allowed
      • Check Your Server Configuration Settings
      • Check the server-side logs and Debug WordPress Issues
      • Try Debugging Application Codes or Scripts
      • WP_DEBUG #WP_DEBUG
    • Like this:
    • Related

There are multiple scenarios or situation in which People also ask –

  • What is Error 405 Not allowed?
  • Why am I getting a 405 error?
  • How to fix HTTP Error 405 Method Not Allowed?
  • What causes 405 Method not allowed?

The 405 Method Not Allowed error in WordPress occurs when the web server is configured in a way that does not allow performing a specific action for a particular website URL. It’s an HTTP response status code that shows that the request method is known by the server but it is not supported by the target resource. As a WordPress website user, there is a significant interdependence between you, your CMS (WordPress Configuration in this case), your web host, and other third-party services. If someone comes across an error page on your website, they are bound to get aggravated and will leave right away.

In this article, you will learn how to fix or resolve the HTTP error 405 method not allowed on wordpress. You just need to simply follow the steps mentioned below 🙂

This can happen because of WordPress Update, new plugin installation or Server Configuration Settings changes.

Like the 404 page not found error, 500 internal server error or error establishing database connection. 405 method not allowed error WordPress is another common problem that most WordPress users face at some point.

All this can result in lost engagement and will hamper sales as well. Out of a plethora of error codes, one particularly common error you should be wary of is the “405 Method Not Allowed” message”. But, you don’t need to be worried sick as you can fix 405 method not allowed error with a little effort and patience.

In this post, we will walk you through what is 405 Method Not Allowed error, how it can appear, and an extensive list of things on how to solve http status 405 method not allowed when calling web services.

Other Common WordPress Errors

  • WordPress White Screen of Death (WSOD) Error
  • 503 Service Unavailable Error WordPress
  • WordPress HTTP Image Upload Error
  • Parse Error: Syntax Error Unexpected in WordPress
  • Pluggable.php File Errors in WordPress
  • Upload: Failed to Write File to Disk” WordPress Error
  • Google Ads Disapproved Due To Malicious or Unwanted Software

Are you encountering frequent website issues?

Our WordPress experts can help you Fix WordPress errors?👍

What is the Error 405 Method Not Allowed?

While maintaining a website, you have to come across lots of hardships and you are going to stuck with some or the other issue. Speaking of issues, you may have to face link breaks, website going down, or pages loading slowly. Now, you may be thinking that these are pretty common issues, but wait, if you ignore them, it may result in poor user experience.

Alas, it is quite unfortunate that some problems are quite tricky to fix, for instance, this is an HTTP response status showing that a web browser has demanded access to one of the pages of your website.

In this case, your web browser has accepted and identified the request but has turned down the particular HTTP method it is using. Practically speaking, the browser is not able to access the page it asked for. Visitors of your website will be encountered with an error page instead of the content they were looking for.

405  Error In Microsoft Edge

fix 405 method not allowed error on wordpress site-nginx-edge

405  Error In Safari

405 Method Not Allowed Error WordPress nginx Safari

405  Error in Firefox

http error 405 method not allowed nginx-firefox

405 Method Not Allowed Google Chrome

405 method not allowed error-nginx-chrome

Keep in mind that 405 Method Not Allowed error and 404 Not Found errors are not the same and they both are significantly different from each other. A 404 Not Found error means the server was unable to find the requested resource and it is, generally, the result of an incorrect URL address.

On the other hand, a 405 Method Not Allowed error means that the requested resource is valid and does exist; however, the HTTP request method used by the browser is not received by your web server.

405 Method Not Allowed Error Variations

You will see an HTTP 405 method not allowed error in the form we have discussed above, different browsers, web servers, and operations systems have their unique ways to present in varied ways. The actual cause of the issue also tends to differ from server to server, this will also change the way the method not allowed 405 error appears.

You may come across the HTTP error code 405 method not allowed in the following variations –

  • method not allowed error 405
  • method not allowed error code
  • http error 405 method not allowed
  • http error 405.0 method not allowed php
  • error 405 method not allowed post
  • 405 method not allowed web api
  • 405 method not allowed laravel
  • 405 method not allowed iis
  • 405 method not allowed flask
  • http status 405 – method not allowed tomcat
  • elasticsearch 405 method not allowed
  • 405 method not allowed stackoverflow

Regardless of their appearance, what makes 405 error intricate is the fact that it can be difficult to solve. This is because it lets you know that something has gone wrong, but they will not tell you about the reason behind the issue. Generally, you will have to do all the research to find the root cause and repair it, if possible.

What Causes Http Error 405 Not allowed?

Let us put the definition of 405 Method Not Allowed error into perspective – HTTP delineate set of methods that bespeak viable actions that can be carried out on the webserver that is being contacted. For instance, this comprises of the following methods –

  • GET – Obtain information related to a described URL resource.
  • HEAD – Get header details related to a URL resource.
  • POST – Send data to the web server, for instance – form data.
  • PUT – Replace the available data for a specific URL along with the new data provided by the client.
  • DELETE – Delete the data from the specified URL.
  • CONNECT – Founded a channel to the server as identified by the target resource.
  • OPTIONS – Explains the available options for communication for the described target audience.
  • TRACE – This method will activate a loop-back test en route to the target resource.
  • PATCH – Executes partial alterations to a resource.

Entirely depending on the goal of the web server, its administrator will organize it to adopt particular methods or ignore others. For instance – if a particular website lacks interactive content, it hardly makes any sense to let the POST method on the web server. In case, this method is not permitted and a client has contacted the server using a POST request, there will be an error 405 method not allowed post, notifying the browser that there is no permission for the method.

Diagnosing the Error 405 Method Not Allowed Message

As we have discussed above that according to Error Message: 405 Method Not Allowed, the user requests from the server, a valid resource with an invalid HTTP method. This is exactly why the technical error lies on the client-side – from the server’s perspective, the client made the wrong request.

Let us now discuss some of the common scenarios that will activate the issue –

  • The origin of the error is URL resource – It needs a method that is not allowed by the webserver.
  • The reason behind the appearance of the error is the misconfiguration of the web server or the software parts that are tasked with acting on a particular URL resource.
  • The hosting provider used by the website administrator has not allowed the HTTP method. This can be commonly seen with the POST method – Keeping in mind the security reasons, Some WordPress hosting providers have blocked this particular method while accessing HTML documents.
  • The administrator of the website has prohibited the HTTP method used by the user agent – this is also done keeping in mind the security element.

Fix or Resolve Error 405 Method Not Allowed?

Before we go ahead and discuss how to fix error 405 method not allowed, make sure you backup WordPress database. When you tinker with your WordPress settings, there are chances that you may accidentally screw-up and backup and restore WordPress database will keep your mind calm and composed as you work through the issue.

You can use a plugin to backup your website or you can ask your WordPress hosting provider to create a copy on a secondary server or use any other method of your choice to fix the 405 method not allowed error issue. 

Once, you have done that, you can move ahead with the troubleshooting process. We have compiled an exhaustive list of methods with the 2-minute guide to fixing HTTP error 405 (method not allowed) that will help you fix the issue once and for all.

Enable the 405 Method Not Allowed Http Post

If you are clueless as to how did you come across HTTP Error 405 Method Not Allowed, then you should first have a look at the software components that are accountable for responding to HTTP requests.

Generally, this is taken care of by the web server. However, if the method is not enabled, a pre-connected Proxy or HTTP handler can also be blamed for the issue. Since the configuration of each application is different, it is important that you first ascertain how the activation or deactivation of the HTTP methods functions for each software.

Input Correct Url to Avoid Http Status 405 Method Not Allowed

One of the common causes of a 405 Method Not Allowed error is to input the wrong URL. Nowadays, most of the web servers incorporate tight security measures and they don’t allow access to any improper URLs to prevent the visitors from accessing the wrong pages. In case of visitors face an issue like 405 client error method not allowed for url, it could be a web server security issue.

Before you move ahead, you have to ensure that you have entered the correct URL of the website you wish to visit.

Roll Back WordPress Updates – Status Code 405 Method Not Allowed

There is no denying that updates come handy. With regular updates, you get to enjoy new exciting features and can help fix bugs and patch security holes. However, despite being a boon, updates can seldom cause some issues.

In case you have updated your WordPress just before the 405 Method Not Allowed error occurs, the new code might be the root cause of the issue. This also applies to the newly upgraded themes or extensions.

If you firmly believe that an update is the main culprit, then you may want to return to the previous version of WordPress. Like we have already discussed, don’t forget to have a full website backup before you ahead with this. , It’s worth reverting back to the previous version of WordPress.

This can be done manually as well, but using a plugin will easily help you roll back WordPress updates. You have a plethora of options at your disposal, but WP Downgrade is effective. With the help of this plugin, you are going to automate the process and you will be able to carry out things without making any error.

Uninstall New Extensions, Modules, Plugins and Themes

Plugins are considered one of the key parts of any WordPress website. With the help of these plugins, you can add a plethora of features and above all, you can automate complex processes without any hassle. If we talk about themes, they are equally important. Without them, you will be spending most of your time doing intricate coding to create an appealing website.

Alas, just as you face issues with software updates, these extensions may also create issues. This is because when you add functionality at any level, it completely changes the way it operates. You may face an issue with the plugin or theme you are using, or any extension may cause a conflict with another part of your website. In such case, you should use Multi-purpose themes. Multipurpose WordPress themes are flexible WordPress templates that can be used to create almost any kind of website imaginable.

Consequently, if you choose to uninstall particular plugins or themes, you may be able to fix the issue. To start this process, you need to go to the Plugins section of the WordPress dashboard. This page will have a detailed list of all the installed plugins –

HTTP Error 405 Method Not Allowed

This is where you can start uninstalling the plugins one by one. When you are done uninstalling the plugins, check whether the issue has been resolved. You have to wait for a while as this process takes some time to complete, but you will get to know as to which plugin was causing the issue.

http status 405 - method not allowed error for rest api

Now, you can repeat the same process with your active theme as well. If your theme or any of the plugin is creating the issue, you need to contact the developer, get rid of the plugin or theme, or you can look for the replacement.

Check if Unexpected Database Changes Causing Error 405 Method Not Allowed

Although you may be able to resolve any plugin or theme-related issue, you cannot be sure that the changes made by your extensions have been completely reverted. This happens with most of the WordPress plugins. Most of the time, they are given complete access to your database as you hit install.

A plugin might be able to make changes to the database records that don’t belong to it, until the developer clearly codes against it, but are alternatively managed by WordPress itself. In this case, the plugin might not be familiar with how to revert those alterations to database records, so it will pay no attention during the installation process.

Identifying the exact issue can be tricky, but if you still feel that the 405 Not Allowed error has been caused by a theme or plugin, then checking your database might help. You can find out by checking the database of your website and go through the tables and records changed by the extension. If you are still not sure, then try getting help from your developer.

Check Your Server Configuration Settings

Your website probably runs on a server that uses one of the two most popular server software options – Nginx and Apache. At the time of publication, both of these web servers make up 84% of the world’s web server software! If you can check software configuration files of your web server for any unintentional handling instructions, you may be able to find the root cause of the 405 Method Not Allowed error.

The key file will help you in making you familiar with the application your web server is using. Let us understand this with the help of an example. Let us assume that your web server is running Apache, you will find a .htaccess file within the root directory of the file system of your website.

In case, your application is on a shared host, you are possibly having a username linked with your account. If that is the case, finding the root directory will be quite easy by following the below-mentioned path –

/home/public_html/

Therefore, you will find the .htaccess file at –

/home/public_html/.htaccess

When you have successfully located .htaccess file, you need to open the file in a text editor and search for the lines that Rewrite directives. In Apache, these are a part of the mod_rewrite module. It defines a text-based pattern that will be matched against all entered URLs. In case, a user requests for a matching URL to your website, the RewriteRule will be redirecting the visitor aptly.

Let us understand this with the help of an example. Following is a RewriteRule that goes with all inbound requests to XYZ.com and retort with a 405 Method Not Allowed error.

Error Message 405 Method Not Allowed

Now, as you can see that there is a flag at the end of the rule marked R=405, it clearly affirms that response codes need to be 405. This demonstrates to the user that there is the availability of the resource; however, the specific HTTP method was unacceptable.

In case, you come across any awkward Rewrite directives in the .htaccess file having a similar instruction, make sure you provisionally comment them out with the help of # character prefix. Now, restart your web server to see if this has resolved the 405 method not allowed nginx or Apache error..

Configuration options for each different type of web server can vary dramatically, this is a list a few popular ones to give you some resources to look through, depending on what type of server your application is running on:

  • Apache
  • Nginx
  • IIS
  • Node.js
  • Apache Tomcat

Check the server-side logs and Debug WordPress Issues

About every web application tends to keep some sort of server-side logs. Generally, web application logs have the complete history of all the tasks done by the software – from the database results it provides, to the pages, it has requested.

Whereas server logs are a bit different, they are linked with the actual hardware that is responsible for running the application. They will time and again provide the details of both the health and the status of all connected services, or just the server itself.

If you are looking for your WordPress server logs, connect to your website through SFTP (Secure File Transfer Protocol). There is a folder known as logs in the root directory, within this folder there are access logs along with your WordPress error logs. They look like this –

  • Access.log
  • Error.log

From there, you need to follow a process that is discussed in the previous point. Examine the logs and take note of anything that looks out of place. You can also refer to the codex for additional debugging details in WordPress.

Try Debugging Application Codes or Scripts

Assuming that none of the above-mentioned steps worked for you, debugging the error is your last line of resistance – that is before you seek the assistance of the developer or hosting provider. Debugging the codes and scripts is one of the effective ways through which you can find the actual cause behind 405 Method Not Allowed error.

Be sure to make a copy of the entire installation ideally, you should do this to an online or local development area, like a staging site. From there, you can start the debugging process step-by-step. Remember, this will vary on your website and its attached software.

WP_DEBUG WP_DEBUG

WP_DEBUG is a PHP constant (a permanent global variable) that can be used to trigger the “debug” mode throughout WordPress. It is assumed to be false by default and is usually set to true in the wp-config.php file on development copies of WordPress.

Debugging in WordPress files

Note: The true and false values in the example are not surrounded by apostrophes (‘) because they are boolean (true/false) values. If you set constants to 'false', they will be interpreted as true because the quotes make it a string rather than a boolean.

It is not recommended to use WP_DEBUG or the other debug tools on live sites; they are meant for local testing and staging installs.

Wrap Up

When you have your website, you are bound to come across issues like Status Code 405 Method Not Allowed. While you shouldn’t panic over them, since there is a resolution for everything. It is imperative that you do your best to know & resolve the issue on how to fix 405 method not allowed Nginx or Apache. Although 405 Method Not Allowed error is a bit tricky, you can always fix the 405 method not allowed error on WordPress site with little troubleshooting.


Get in touch with our team of WordPress Experts To Solve Errors on Your WordPress Site.


Other Useful Articles (In-Depth)

  • This account has been suspended WordPress issue
  • How to disable directory listing in WordPress
  • WordPress site redirecting to spam site
  • How To Fix hacked Godaddy hosted WordPress site
  • Fix Japanese Keywords hack In WordPress Site
  • How to Remove Blackhat SEO Spam in WordPress Site?
  • How to Prevent SQL injection in WordPress
  • Best WordPress Security Plugins 2023
  • WordPress File And Folder Permissions Error
  • Common WordPress Vulnerabilities 2023

В этой статье мы объясним, что такое ошибка 405 и как она может проявляться. А также расскажем, как исправить эту ошибку, возникающую на WordPress-сайте.

  • Что означает ошибка 405 Method Not Allowed
    • Google Chrome
    • Safari
    • Firefox
    • Microsoft Edge
  • Вариации ошибки 405
  • Как исправить ошибку 405 Method Not Allowed на WordPress-сайте
    • Проверьте, правильно ли вы ввели URL-адрес
    • Откат недавно установленных обновлений WordPress
    • Удалите новые плагины и темы оформления
    • Проверить любые непреднамеренные изменения в базе данных
    • Проверка конфигурации сервера
    • Просмотрите журналы сервера
    • Отладка кода приложения или скриптов
    • Что делать, если ни одно из этих решений не помогло
  • Заключение

Ошибка 405 Method Not Allowed возникает, когда браузер запросил доступ к одной из страниц сайта, но веб-сервер отклонил определенный в запросе HTTP-метод. Получается, что браузер не может получить доступ к запрашиваемой странице. Вместо интересующего пользователей конвента они увидят страницу с ошибкой.

Google Chrome

Ошибка 405 Not Allowed в Chrome

Safari

Ошибка 405 Not Allowed в Safari

Firefox

Ошибка 405 Not Allowed в Firefox

Microsoft Edge

Ошибка 405 Not Allowed в Microsoft Edge

Ошибку 405 не следует путать с кодом ответа 404 Not Found. Он означает, что запрошенный URL-адрес не найден или введен неправильно. Сообщение об ошибке 405 подтверждает, что запрашиваемая страница, но для выполнения запроса использовался неподдерживаемый HTTP-метод.

Это код ответа HTTP указывает, что метод запроса известен серверу, но не поддерживается целевым ресурсом.

Вот некоторые варианты отображения ошибки:

  • 405 Not Allowed;
  • Method Not Allowed;
  • HTTP 405 Error;
  • HTTP Error 405 – Method Not Allowed;
  • HTTP 405 Method Not Allowed.

Самой распространенной причиной возникновения ошибки 405 является неправильный URL-адрес. Большинство веб-серверов блокируют доступ пользователей к несуществующим страницам сайта.

Если вы обновили WordPress незадолго до того, как стало появляться сообщение об ошибке 405 Method Not Allowed, то именно обновление может являться причиной возникновения проблем. Это также относится к любым плагинам и темам оформления, которые вы недавно обновили.

Самый простой способ откатить обновления WordPress – использовать специальный плагин. Самый эффективный из них – WP Downgrade. Он в значительной степени автоматизирует процесс обновления.

Плагины и темы оформления могут создавать проблемы. Это связано с тем, что добавление любой функциональности на сайт влияет на его работу. Ошибка 405 быть связана с плагином или темой оформления, которую вы используете. А также если конкретное расширение конфликтует с другой частью CMS.

Удаления определенных плагинов или тем оформления может устранить ошибку 405 Method Not Allowed. Для этого перейдите в раздел «Плагины» панели администрирования WordPress.

Удалите новые плагины и темы оформления

Страница плагинов в WordPress

После удаления каждого плагина не забудьте проверять, устранена ли возникшая ошибка. Этот процесс позволит вам точно определить, какой плагин вызывает проблему.

Удалите новые плагины и темы оформления - 2

Как деактивировать плагин в WordPress

После проверки плагинов можно приступить к деактивации (удалению) используемой темы.

Рассмотренный выше способ не гарантирует, что изменения, внесенные расширениями, будут полностью отменены. Это особенно актуально для WordPress-плагинов. Многие из них могут изменять записи в базе данных, которые влияют на работоспособность WordPress.

Если вы уверены, что плагин или тема оформления являются причиной возникновения ошибки 405 Method Not Allowed, проверка используемой базы данных полностью решит проблему. Для этого необходимо открыть базу данных сайта и вручную просмотреть таблицы и записи, измененные расширением.

Ваш сайт, скорее всего, работает на сервере, который использует Apache или Nginx. На их основе базируется более 80% всех серверов. Проверка файлов конфигурации сервера на наличие неподдерживаемых инструкций поможет решить причину возникновения ошибки 405.

Например, если веб-сервер работает под управлением Apache, то конфигурационный файл .htaccess располагается в корневом каталоге сайта. В него можно попасть, перейдя по следующему пути:

Таким образом, файл .htaccess будет располагаться по адресу:

/home/public_html/.htaccess

Откройте файл .htaccess в текстовом редакторе и найдите строки, которые используют директивы Rewrite. Они являются частью модуля mod_rewrite в Apache и определяют текстовый шаблон, который будет сопоставляться со всеми введенными URL-адресами. Если посетитель сайта запрашивает URL-адрес, подходящий под правило RewriteRule, оно перенаправит посетителя соответствующим образом.

Вот простой пример правила RewriteRule, которое сопоставляет все входящие запросы и отвечает кодом ошибки 405 Method Not Allowed

Проверка конфигурации сервера

Пример правила RewriteRule

В конце записи правила есть флаг R = 405. Поэтому полученный код ответа будет 405. Если вы обнаружите другие «странные» директивы Rewrite в файле .htaccess, попробуйте временно закомментировать их, используя префикс #. После этого перезапустите веб-сервер, чтобы увидеть, решило ли данное изменение возникшую проблему.

Почти каждое веб-приложение хранит журналы на стороне сервера. Они содержат полную историю операций, совершенных приложением.

Журналы сервера немного отличаются. Они часто предоставляют подробную информацию о состоянии всех подключенных служб или даже только самого сервера.

Чтобы просмотреть логи сервера, вам нужно подключиться к вашему сайту через протокол защищенной передачи файлов (SFTP). В корневом каталоге найдите папку logs. В ней находятся журналы доступа и журналы ошибок WordPress:

  • Access.log;
  • Error.log.

Теперь просмотрите журналы и проверьте все записи, которые выглядят странно.

Если ни один из предыдущих методов не помог, тогда проблема связана с пользовательским кодом. Для ее решения нужно провести отладку кода.

Для этого нужно скопировать весь сайт на промежуточный сайт. После этого можно будет провести пошаговую процедуру отладки.

Если ни один из перечисленных методов не помог, то возникла более сложная проблема. В этом случае стоит обратиться к вашему хостинг-провайдеру.

К счастью, в большинстве случаев ошибку 405 Method Not Allowed можно легко исправить с помощью быстрой отладки.

Понравилась статья? Поделить с друзьями:
  • Http error 405 asp net core
  • Http error 404 торрент
  • Http error 404 как исправить ошибку
  • Http error 404 yandex
  • Http error 404 wordpress