Custom URL Rewrites

1 minute read

Have you ever needed a special URL that doesn’t match your module and controller name? I mean sure /mymodule/mycontroller/myaction is always nice to have as a URL if the naming makes sense. However, sometimes you need a prettier URL to make those SEO guys happier (you know, the ones that make the internet so much “better” for searching). If you are not already aware, Magento can help with that. Perhaps you’ve seen the URL Rewrites menu under Catalog in the admin panel. Maybe you’ve dismissed it thinking it was only for products or categories. Hold on. It is so much more.

With the URL Rewrite Management menu, you can add a rewrite that sends /my-pretty-url-that-makes-seo-guy-really-happy to /mymodule/mycontroller/myaction. What’s more, you can add code to have this rewrite done for you when anyone installs your module (especially useful for keeping your dev/test/production environments in-sync or if you have multiple rewrites to add). Here is a sample of how to add a rewrite. You can out this in your mysql4-install/upgrade script to have Magento run it for you:

<figcaption></figcaption>

1
2
3
4
5
6
7
8
<span class="line"><span class="x">Mage::getModel('core/url_rewrite')</span>
</span><span class="line"><span class="x">-> setStoreId(1) // make sure to put the correct store</span>
</span><span class="line"><span class="x">                 // number here if you use multiple</span>
</span><span class="line"><span class="x">                 // stores.</span>
</span><span class="line"><span class="x">-> setIdPath('my-uber-cool-url.html')</span>
</span><span class="line"><span class="x">-> setRequestPath('my-uber-cool-url.html')</span>
</span><span class="line"><span class="x">-> setTargetPath('mymodule/mycontroller/myaction')</span>
</span><span class="line"><span class="x">-> save();</span>
</span>

</figure>

You might think you’ll never need this, but I can tell you I’ve used it twice now in the last 45 days.

Categories:

Updated:

Leave a Comment