Restrict Direct Access to Magento 2 Controller URLs

In the vast world of Magento 2 development, a common challenge developers face is preventing direct access to specific URLs. Direct access can result in issues like the bulk generation of promo codes, leading to potential abuse of discounts and financial loss for the business. Additionally, automated scripts (bots) could repeatedly hit the URL, causing unnecessary load on the server.

In this blog, we’ll explore a seamless solution to this problem, ensuring that URLs are accessible only through Ajax requests.

If you don’t know how to create a controller, please check here

Solution:-

public function execute()
{
    $result = $this->jsonResultFactory->create();
    if ($this->getRequest()->isAjax()) {

    // Your AJAX specific code logic here

        $data = ['message' => 'Hello'];
        $result->setData($data);
        return $result;
    }

    // If it's not an AJAX request, handle accordingly

    $data = ['error' => true, 'message' => __('Direct access is not allowed.')];
    $result->setData($data);
    return $result;
}

The above code guarantees that it will only run when the URL is accessed via Ajax requests. If accessed directly, it gracefully redirects to a “noroute” page, preventing any undesired consequences.

By implementing this strategy, Magento 2 developers can maintain control over URL access, ensuring a smooth and secure experience for both users and search engines. Happy coding!

Thank you for reading my Article! Feel free to share your thoughts or ask any questions in the comments section below and spread the word by sharing. Your engagement is appreciated!

Leave a reply

Your email address will not be published. Required fields are marked *

Cookies Notice

Our website use cookies. If you continue to use this site we will assume that you are happy with this.