WordPress attachment page redirects to file URL

I was developing a WordPress theme for one of my customers, I created a template for attachment post type attachment.php but unfortunately, the page was redirecting me to the file URL.

I reviewed the WordPress template hierarchy, to check for any changes in the new WordPress version, I also tried to create templates based on file extension, but none of them worked.

I noticed that WordPress was able to reach the attachment template page before redirecting. I just used: echo 'OK'; exit; in the template and was able to see the OK. I started to deactivate the plugins to see if any of them is causing the redirect and yes! One of the installed plugins called Yoast SEO creates that behavior by default.

Most of the templates do not include a special template for attachments, that is why Yoast SEO has assumed that it would be better from an SEO approach to redirect attachment URLs to the attachment itself.

If you are using Yoast SEO, go to SEO » Search Appearance » Media & attachment URLs. If you want to stop that redirect behavior, switch that option to NO.

Have a nice day!

Leave a Reply

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