URL Rewrites for magento custom module - .htaccess

I am trying to create some user friendly URLs for my module.
The module name is landing. Right now, I use the index controller and index action, and then grab a string "page" from the URL an grab my object based on that. So, my URLs look like this:
http://www.example.com/landing/index/index/page/CoolPage
My current idea is to structure this url as /landing/{page}, so that it would be just:
http://www.example.com/landing/CoolPage
At first, I tried accomplishing this using htaccess. I have the following:
RewriteRule ^landing/([a-z\-]+)(/)?$ landing/index/index/page/$1 [R,L]
Which works but does a redirect instead of a rewrite. I also tried it with just [L] and without the [] on the end, but I just end up at my 404 page.
Ideally I would use a config rewrite, as that could be packaged with my module, but I can't find any documentation on using them like this. I would be happy using .htaccess or even a db based rewrite, if it worked as desired.
Is there a way to do a rewrite like this in Magento?

I think I had the exact same request from a client some time ago and here is how I managed it, which I think is the easiest and simpliest way...
Actually, it is possible to make a rewrite right into your module's config.xml file.
In this example, all URLs like
http://www.domain.com/landing/whatever
will be rewritten to
http://www.domain.com/landingpage/page/view/whatever
Config.xml
<?xml version="1.0"?>
<config>
<modules>
<My_LandingPage>
<version>0.0.1</version>
</My_LandingPage>
</modules>
<frontend>
<routers>
<landingpage>
<use>standard</use>
<args>
<module>My_LandingPage</module>
<frontName>landingpage</frontName>
</args>
</landingpage>
</routers>
</frontend>
<global>
<!-- Rewrite requested routes -->
<rewrite>
<my_landingpage_page_view>
<from><![CDATA[#^/landing/#]]></from>
<to>/landingpage/page/view/</to>
<complete>1</complete>
</my_landingpage_page_view>
</rewrite>
</config>
Controller
<?php
class My_LandingPage_PageController extends Mage_Core_Controller_Front_Action {
/**
* View page action
*/
public function viewAction() {
// Get the requested path (/landing/whatever)
$pathInfo = $this->getRequest()->getOriginalPathInfo();
// Extract the requested key (whatever)
$pathArray = explode('/landing/', $pathInfo);
$requestedKey = $pathArray[1];
// So, from there you can use $requestedKey to load any model using it.
// This is also where you will load and render your layout.
}
}
Side note about layout
As the real controller action that is called is "landingpage/page/view", if you need some layout for this module, its handle will be <landingpage_page_view>.

This is a textbook custom router case if I've ever seen one. You can take the approach of the CMS router and adjust the path on the request object so that your controllers can match using the Standard router.
Your other alternative is to create an indexer to create rewrites for your module's entities and store them in the core_url_rewrite table.

Related

How to redirect Hard Coded Urls to hard coded Urls without hitting errorAction?

I have almost one thousand links which I want to redirect when a request is made specifically to those URLs. e.g
Redirect http://serverAddress/app/2017/06/09/8-20-taraweeh/ http://serverAddress/app/prayer/8-or-20-Rakat-for-Taraweeh
I am trying this code in .htaccess file but the problem is that when I enter the Url, instead of hitting the .htaccess code it first hits the Yii app and check if the Url exists, if not exists(definitely does not exist) it takes me to the error page.
Now I cannot define a rule because as you can see the URL after the app is changing, I cannot define a generic rule. So I have to hard code in my yii2 app.
Question:
How to Hard code Url redirections in yii2?
You could define a rule something similar:
'<year:\d+>/<month:\d+>/<day:\d+>/<title>' => 'site/redirect'
Then in your SiteController use can use redirect in the controller action:
public function redirectAction($year, $month, $day, $title) {
$newUrl = .... // compute new URL based on the parameters
return $this->redirect($newUrl, 301);
}

how to remove id of div in url with htaccess

I am having in an url the id of a div (#latest) like this at the end:
http://example.com/discussion/64/moderators-only#latest
http://example.com/discussion/32/bugs#latest
// and so on...
How can i remove the #latest in all these url's with htaccess?
You can't. Anything after the # is a URL fragment that the browser never even sends to the server. So the only thing the webserver sees is: http://example.com/discussion/64/moderators-only. So nothing in the htaccess or even in the apache config can do anything about those fragments.
You'll need to employ some sort of javascript or client-side solution if you want to remove it. But a better question is, do you need this in order to display the content correctly? If so, then how do you expect to display the content if this is gone?

ModX redirect based on query string (Revolution 2.3)

I am rebuilding a website in ModX and I want to redirect the old URLs to the new ModX pages, automatically.
An old URL is of the form, http://www.oldsite.com/?pg=2
Every page is like this, so I need to manually map the old page IDs to the new ModX resource IDs. For example, pg=2 is the contact page, which is now resource ID 11, so I'll end up with a map like [2=>11, 3=>15, etc]
If I tweak the main index.php right in the docroot, this does exactly what I want:
/* execute the request handler */
if (!MODX_API_MODE) {
if (isset($_GET["pg"])) {
if ($_GET["pg"] == 2) {
$url = $url = $modx->makeUrl(11);
$modx->sendRedirect($url);
}
else {
// Page is set, but we don't have a redirect for it.
$modx->handleRequest();
}
}
else {
$modx->handleRequest();
}
}
However, I am not happy with hacking index.php directly. I'm a bit short of ModX experience to know exactly where to put this code. I tried:
A snippet, which I then called from my HTML header before any HTML, but the redirect stopped working
The Redirector extra, but this doesn't work on the QUERY_STRING, I don't think
Any insight is appreciated, for the best place to package this code, or a pointer towards an Extra I should be using.
The solution that worked for me, following Sean's insights below, is a plugin. The plugin code is below. For other plugin newbies like me, ensure you visit the "System Events" tab to enable your plugin for the event you're trying to access.
<?php
if ($modx->event->name == 'OnWebPageInit') {
// Look to see if the GET params include a pg. If they do, we have a request
// for one of the old pages.
if (isset($_GET["pg"])) {
// Map the old pg IDs to the new resource IDs.
if ($_GET["pg"] == 2) {
$url = $modx->makeUrl(11);
}
// Add more here...
// When done trying to match, redirect.
// But only do the redirect if we found a URL.
if (isset($url)) {
$modx->sendRedirect($url, array('responseCode' => 'HTTP/1.1 301 Moved Permanently'));
exit;
}
}
}
My preference to do this is in the .htaccess file with redirects or url rewriting - that way you can send the redirect and the response code ~before~ modx has to process anything [save a bit of overhead]
if you still want to do this in modx, take a peek at the sendRedirect docs & send the correct response code [so google gets the hint that the page has actually moved] Note: the $responseCode option is depreciated and you should use it in the options array these days:
$modx->sendRedirect('http://modx.com',array('responseCode' => 'HTTP/1.1 301 Moved Permanently'));
I do agree with not hacking the index.php file, only will cause you grief. What you want to do is place your redirect code in a plugin. Check the Modx API docs for the appropriate event for it to fire on - perhaps: OnWebPageInit will do the trick. Sorry, I don't know exactly which one will work.
HOWEVER ~ IMPORTANT NOTE!
Not all events are actually active, they may show up in the modx manager but don't actually do anything, you will just have to test or dig through the code to find out. [or ask in the community] Again, sorry, I don;t know for sure which ones work and which don't.

How does IIS URL Rewrite handle # anchor tags

I'm struggling to find any information on how best to handle URLs with anchor tags, like the #foo in www.example.com/index.html#foo
Our current situation is trying to use a Rewrite map for a URL with an anchor tag, but it is being trumped by another Rewrite mapping.
e.g.
<add key="index.html#foo" value="bar1.html" />
<add key="index.html" value="bar2.html" />
<!-- A request to index.html#foo is being redirected to bar2.html,
not bar1.html as expected -->
Does URL Rewrite include this in the URL? Or is available via one of the variables? Is there documentation on this?
(I've also tried searching on "fragment identifier", "#" "hash" "hash tag")
The portion of the URL after # (fragment) is never passed to the server as per HTTP spec, therefore, URL rewrite won't see it.
Source:
Does IIS throw away the URL fragment on custom error pages?

Joomla - Custom component url rewrite

I have the following component #
?option=com_tmportal&module=user&task=main
I've enabled url rewriting and setup the htaccess file which is all working correctly, how would I create a rewrite rule that allows me to access the component above by simply doing:
/portal/ = ?option=com_tmportal
or
/portal/user = ?option=com_tmportal&module=user
or
/portal/user/main = ?option=com_tmportal&module=user&task=main
Thanks for any help, much appreciated :)
You haven't specified Joomla version so I'm assuming 1.6/7/2.5 in my answer.
Short Answer: If you're using Joomla!'s default .htaccess then all you have to do is create a Joomla! menu to each of your components views with the right alias eg. portal for your default component access ie. ?option=com_tmportal.
This is what the default .htaccess does it passes all of the elements after the base URL to index.php to help select the component and view.
Longer Answer
When you create a component for Joomla! you specify the menu settings for each view using an XML file usual the same name as the view file in it's view/tmpl/ directory.
Typically the url to a specific view & task in a component would look like these:
?option=com_mycomponent
?option=com_mycomponent&view=userdetails
?option=com_mycomponent&view=userdetails&task=main
Joomla!'s framework will automatically use the view & task params to get your components correct controller and view (or sub-view). I'm not sure that it does anything with the module param that you have in your URL's so I'd guess you're trapping and processing that yourself.

Resources