Yii2 Trailing Slashes in URL is breaking the route - .htaccess

I configured UrlManager in a project and It was working the way I wanted.
Now i tried to add a content whose name contains a trailing slash but i get an error 404 (Object not found).
For example:
www.test.com/article/detail/id_of_article/title_of_article
title_of_article = People are ... => Work
title_of_article = 1/3 of People are ... => Doesn't Work (Object not Found)
The Trailing Slash is breaking the Url although it is encoded in %2F
This is how i create url:
Html::a(Html::encode($model->title),
['article/detail', 'id' => $model->id, 'title' => $model->title])
I don't really know how I can deal with that.

For This , the best solution is to use slug names.
Instead of id and title, take one more field called slug_name in your database.
On Add or update of any record generate slug name and store in db.
For generating slug name, you can use custom function as below.
public function getSlugName($id,$title)
{
$slug=$id;
if(isset($title) && $title!=null)
{
// remove all spacea
$slug.='-'.str_replace(' ','-',strtolower($title));
}
$slug=preg_replace('/[^A-Za-z0-9\-]/', '', $slug); // Removes special chars.
$slug=str_replace(array('--'), '-', $slug); // remove multiple --
return $slug;
}
This function will return you uniq name. So you can use it in url.
This is also help in SEO.

Could be you need URL normalization
Since version 2.0.10 UrlManager can be configured to use UrlNormalizer
for dealing with variations of the same URL, for example with and
without a trailing slash.
NB by default UrlManager::$normalizer is disabled. You need to explicitly configure it in order to enable URL normalization.
see how here http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#url-normalization

There is an encodeParams property of UrlRule. Please try with that.

Related

MVC route to content to avoid other routes from matching?

In my MVC project I have a route like this:
routes.Add("MyRoute", new MyRoute("{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }));
I also have some bundles (showing only constructor with URL here):
new Bundle("~/Scripts/companyname", typeof(JsMinify));
new Bundle("~/Content/themes/companyname/css", typeof(Microsoft.Web.Optimization.CssMinify));
new Bundle("~/Content/skin/css", typeof(Microsoft.Web.Optimization.CssMinify));
new Bundle("~/Content/companyname_css", typeof(Microsoft.Web.Optimization.CssMinify));
new Bundle("~/Content/print_css", typeof(Microsoft.Web.Optimization.CssMinify));
I want those bundles to not be matched by "MyRoute". How can I achieve that?
Found it. This is what RouteCollection.IgnoreRoute is for. I do find the documentation in this area pretty scarce, so I'll add a few details here.
routes.IgnoreRoute("Content/{*pathInfo}");
routes.IgnoreRoute("Scripts/{*pathInfo}");
Those lines tell the routing system to ignore URL:s that start with Content/ and Scripts/ respectively, and has "anything" after the /. The asterisk * in {*pathInfo} means that the pathInfo token should be assigned the remainder of the URL.
I have not been able to determine if the name pathInfo matters, or could be anything, but it appears that the pattern needs a placeholder there, with the leading asterisk, to match anything after the /.

Liferay friendly url with optional param

My URL have some params, so i use friendly URLs to solve that ugly URL liferays generates by default.
couple of this params sometimes are empty, that mean its no needed, but other times give me some ID i use for a query.
Example param not null:
https://myliferay.com/example-portlet/-/example-portlet/search/idTable-7
//it works
Example null param:
https://myliferay.com/example-portlet/-/example-portlet/search/idTable-null
//it works
With null param it works, but i dont like to see a null on my URL.
I want something like "":
https://myliferay.com/example-portlet/-/example-portlet/search/idTable-
//Doesnt work
But it doesnt work, its like the URL doesnt match the friendly URL pattern when a param its empty.
<route>
<pattern>/search/idTable-{idTable}</pattern>
<generated-parameter name="idTable">{idTable}</generated-parameter>
<implicit-parameter name="p_p_lifecycle">0</implicit-parameter>
<!--more implicit params-->
</route>
How can i specify optionality of a parameter?
Its like all vars of friendly url use a regex. You can change/override this regex like this: {idTable:\d}
<route>
<pattern>/search/idTable-{idTable:.*}</pattern>
<generated-parameter name="idTable">{idTable}</generated-parameter>
<implicit-parameter name="p_p_lifecycle">0</implicit-parameter>
<!--more implicit params-->
</route>
i used .* as regex for 0 or more characters, but i dont know if it will bring me problems later. If anyone knows why is not a good idea to use that regex comment it please.
Upgraded the regex with \d* to search only digits or empty: {idTable:\d*}
Info: Making URLs friendlier 7.0

Prestashop Friendly URL's

I've been trying to create a second option of url rewrites to a product inside prestashop. In the standard Prestashop installation at the SEO & URL's section i've got the following products url build-up:
{category:/}{id}-{rewrite}-{ean13}.html
This creates the following products url:
https://www.example.com/{category-name}/{product-id}/{product-name}/{ean13}.html
What i would like to add is an option for various reasons to acces a products page through the following url build up:
ean/{ean13}.html
The result url would be something like the following example:
https://www.example.com/ean13/{ean13}.html
NOTE, ID is a standard required field of the url build up, this means that i can't use: "Just ajust the url build up" as an answer.
Is there a module, addon, or piece of code out there that would be able to generate these kind of structures?
I did find some "Remove ID's from pretty url's" modules but that doesn't give me the result i'm searching for. Only partially since it only removes the ID's.
It wouldn't be a problem if it's a redirect to the standard url build up as mentioned in the first {code} segment. I know i could write rewrite rules in my .htacces file but to do this for every product would be a lot of work so i was wondering if there is a more easy way of achieving this.
As always thanks in advance!
If you're fine with redirect to standard URL then the solution is quite easy with a module.
Create a module that uses hook moduleRoutes and configure a friendly URL to use module controller
Create a module front controller
Run a db query in your custom controller to check if a product with requested EAN exists
Redirect to product page if product exists, otherwise to 404 page or something
I assume you know how to write modules and controllers, so I won't write entire code just the relevant bits.
Hook moduleRoutes in module class.
In this hook you can configure a friendly URL for your custom controller.
public function hookModuleRoutes()
{
return [
'mymodulename-mycontrollername-root' => [
'rule' => 'ean13/{:ean13}.html',
'controller' => 'mycontrollername',
'keywords' => [
'ean13' => ['regexp' => '[0-9]+', 'param' => 'ean13']
],
'params' => [
'fc' => 'module',
'module' => 'mymodulename'
]
]
];
}
So visiting https://www.example.com/ean13/12345.html will run your module controller and a GET variable ean13 will have a value of 12345.
Then create mycontrollername module controller where you can use postProcess() method to check if EAN exists.
public function postProcess()
{
$query = new DbQuery();
$query->select('id_product')
->from('product_attribute', 'pa')
->where('pa.ean13 = ' . (int)Tools::getValue('ean13'))
$productId = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
if ($productId) {
Tools::redirect($this->context->link->getProductLink($productId));
}
Tools::redirect('pagenotfound');
}
In query we check in product_attribute table as product combinations can have their own EAN13 and you also want those EAN13's to redirect to product page.
The basics of this answer is most commonly used to replace core product search controller with a custom and SEO friendly one.

How to use add_rewrite_rule function, while permalink structure is disabled?

I am using the add_rewrite_rule() function to modify my URL structure.
I'm wanting to use add_rewrite_rule to add a custom rule but these rules only get added in when other than default settings are selected in my permalink settings area.
i.e. in the settings there are following options:
- Default http://localhost/wordpress/?p=123
- Day and name http://localhost/wordpress/2014/08/14/sample-post/
- Month and name http://localhost/wordpress/2014/08/sample-post/
- Numeric http://localhost/wordpress/archives/123
- Post name http://localhost/wordpress/sample-post/
- Custom Structure http://localhost/wordpress
So, when I select other then 'Default', my add_rewrite_rule() function works, but while selecting 'Default', the function doesn't seem to be work. So please suggest me how to work the function in any condition. Any help would be Appriciated.
Update:
I think the problem lies here:
When I use this, while selecting 'Default':
get_option('permalink_structure');
I got nothing.
While in the other cases, there are some values like:
/%postname%/
/archives/%post_id%
/%year%/%monthnum%/%postname%/
The Default permalinks, or so called "Ugly" permalinks, are not adding anything to the .htaccess file, so the Apache rewrite engine is not enabled. Without the rewrite engine, no rewrites can be done. So the short answer is that rewrites are not possible with Default permalinks.
I can recommend you to use rewrites along with query vars. When adding a rewrite rule, pass your custom data to a query var, and build the functionality around that query var. This way your functionality will work in all situations and with all permalink types.
So for example if you have the following rule:
add_rewrite_rule('^sometest/([^/]*)/?','index.php?custom_query_var=$matches[1]', 'top');
and you have the custom_query_var added as a query var by using the following code:
function add_query_vars_filter( $vars ){
$vars[] = "custom_query_var";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
then when Default permalinks are selected, the following URL would work for you:
http://yoursite.com/index.php?custom_query_var=abc
and if "Pretty" permalinks are selected, the URL rewriting would work and your URL would look the following way:
http://yoursite.com/sometest/abc/
which is basically the best that can be achieved with rewrites.
I agree with #Martin. Here's a resource that will help https://core.trac.wordpress.org/ticket/15235
use this:
function my_add_query_vars( $qvars ) {
$qvars[] = 'business-coaching';
$qvars[] = 'country';
$qvars[] = 'territory';
$qvars[] = 'region';
return $qvars;
}
add_action('query_vars', 'my_add_query_vars');
//Write the rule
function add_analytic_rewrite_rule()
{
// Regex:The regex to match the incoming URL is:business-coaching(/([^/]+))?(/([^/]+))?(/([^/]+))?/?
// Redirect Rule :The resulting internal URL: `index.php` because we still use WordPress
// `pagename` or page_id=45 because we use this WordPress page
// `country` : we will assign the first captured regex part to this variable
// `territory` we will assign the second captured regex part to this variable
// `region` we will assign the third captured regex part to this variable
add_rewrite_rule('business-coaching(/([^/]+))?(/([^/]+))?(/([^/]+))?/?','index.php?page_id=45&country=$matches[2]&territory=$matches[`enter code `enter code here`here`4]&region=$matches[6]','top');//superfinal
}
add_action('init', 'add_analytic_rewrite_rule');

Codeigniter routing URL with product name to product id

I need to redirect the URLs like this http://mysite.com/store/store-name to http://mysite.com/stores/products/store-id. Note that i need to get the store id from the database. So is it possible to do db operations in routes.php?
And in documentation the syntax is give as $route['store/:any']. How to get the value of second parameter here which is mentioned as :any.
There's not really any good nor simple way of running database queries through the routes. You can however have in the beginning of the controller function a validation.
I asume your store-name is some sort of slug for the product? Basicly you can validate if value is numeric or not, and if not find by slug and then redirect.
config/routes.php
$route["store/(.*)"] = 'stores/products/$1';
/* () and $1 together passes the values */
controllers/stores.php
/* Class etc. */
function products($mix) {
if (is_numeric($mix))
$int_id = $mix;
else {
$row = $this->get_where('products', array('slug' => $mix))->row();
$this->load->helper('url');
redirect("stores/products/{$row->id}");
}
/* Do stuff with the $int_id */
}
This asumes that you have:
A table named products
A column named id that's your products id
A column named slug that that's based on your store-name
I may be a little late to the party, but I may have an alternative suggestion.
I use the following for my routes:
http://mysite.com/store/1/store-name
Reason being... Based on your method, if you create
http://mysite.com/store/store-name
but then after a period of time (of which no doubt Google has indexed your page) you decide for what ever reason you have to change the name of the store to "Wonderful store name", you would naturally change your link to
http://mysite.com/store/wonderful-store-name
Which kills your SEO and any index links.
My solution of using http://mysite.com/store/1/store-name means that you can change store-name to anything you want, but it will always reference 1 meaning the user will still see the related page.
Anything is possible with CodeIgniter routes. Its all in the way you code it. Routing in CI is really flexible. You can use regular expressions besides the standard CI wildcards (:any)(:num). You can even add prefixes or suffixes to the path variables if you have to like:
$route['store/(:any)'] = "redircontroller/redirfunction/$1";
// for instance the namelookup method of the mystores controller
$route['stores/products/(:any)'] = "mystores/namelookup/$1";
You get the second parameter(and third and so on) by defining the variables in your route value which get passed to the controller method you define. If 'products' in you new url is also a variant you should start your wildcard expression there instead. You could also pull parameters out of the url using the URI class ($this->uri->segment(n)).
You don't, however, do database operations in routes.php. You do your database operations in the controller where you route to. My guess is that you'll have to match the store id using whatever is used in the url in a query.
In any case the path that you are using the routes file for is the path the user will see. To do the redirect you have to accept the original path and then redirect the user to the new path like so:
// in some controller that's attached to the original url
public function redirfunct($var){
$this->load->helper('url');
redirect(base_url('stores/products/' . $var));
}
I hope this helps you.
Yes that is easy, you only need to show the ID instead of the name,
you must be doing like storeName> Click to view details
Make it as
storeId> Click to view details
and when you are passing the parameter to the database, change the check of mysql, change it to id instead of name , that can be some like
" select yourRequiredColumn from table_name where id=".parameter."
Thanks

Resources