How to remove direct product url from magento? for example

Instead of http://example.com/product1.html All product url should have category name in path.

Like http://example.com/category-name/product1.html

Note: I dont want to access product with direct link. I m aware that we can add category path in product url with enabling below settings.

go to Store -> Configuration -> Catalog -> Catalog -> Search Engine Optimization -> "Use Categories Path for Product URLs" set to "Yes"

  • if you searching and in search listing page if you click on any product then you not have other option except direct url for receptive product. and in magento one product can be assign to multiple category so which category you will need in url. – Kanhaiya lal May 5 '18 at 16:02
  • True, Agree to your point. But I guess we can change the product url in search page with category.In my case one product will assign to one category only – Shivam May 6 '18 at 5:18

You will need to set SEO option in admin for this

Admin -> Stores -> Configuration -> Catalog -> Search Engine Optimization -> Use Categories Path for Product URLs -> Yes


I think you can use postdispatch event for the same


You can check the action called and based on that you can redirect product to path with contain category level. To get the product action and check product you can use

$event = $observer->getEvent();
$request = $event->getControllerAction()->getRequest();
$request->getFullActionName() // need to check if action is 'catalog_product_view'

You can get current product from registry object.

| improve this answer | |
  • Thanks Akhilesh. Nice to hear from you. but actual I dont want to redirect customer from url. I dont want to generate a direct product url in system. – Shivam May 5 '18 at 12:42
  • I understand...In magento product URL created by URL_Rewrite concepts where system adding category path and direct URL to url rewrite table. And in system you can have product without any category assigned. so either in your case if any product URL open directly you can sent it to no route. It oblivious you can't restrict customers to prevent using direct URL. – Akhilesh Patel May 5 '18 at 12:46
  • Okay, We can prevent them to using direct url. if we not generated direct url in system. – Shivam May 5 '18 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.