I have an yii advanced app with frontend and backend.
What I try to achieve is that I can access the frontend with the name of a customer.
Example (local): http://localhost/myproject/frontend/web/customer1 should become http://localhost/myproject/frontend/web/customer1/site/login at first visit
And after login the name of the customer should stay in the URL. At the moment the URL changes after login to http://localhost/myproject/frontend/web/
Info:
customer is a GET parameter. It should always be the first argument after http://localhost/myproject/frontend/web/ but I don't want to specify the argument in each redirect or custom link. I hope there's a way to keep this argument and pass it to each of the following site changes.
What I have tried so far:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
'<controller>/<action>' => '<controller>/<action>',
'<customer:\w+>' => '/site/login',
]
],
But this is not working. I can only access the login page and afterwards the customer name is not showing anymore in the URL.
My .htaccess file looks like this:
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
I'm really appreciate any hints on this topic.
To prepend customer name to all urls modify your url rule:
<customer:\w+>/<controller>/<action>' => '<controller>/<action>,
If you now call yii\helpers\Url::to(['site/index', 'customer' => 'customer'])the output will be as you want - /customer/site/index.
Howewer calling it like that in entire project is not flexible approach.
Most of the times Url::to() method is used for generating internal urls.
If you pass array in $route, it will call Url::toRoute(). So you can simply override that method in your custom component.
namespace frontend\components;
use yii\helpers\Url as BaseUrl;
class Url extends BaseUrl
{
public static function toRoute($route, $scheme = false)
{
$customer = ... // Get saved after login customer name (for example from the session)
$route['customer'] = $customer;
return parent::toRoute($route, $scheme);
}
}
Then you can simply call frontend\components\Url::to(['site/index']) to achieve the same result.
Alternative way of customizing helper classes described in official documentation here.
Update:
Also this url rule '<customer:\w+>' => '/site/login', is redundant and the url should be just site/login, because any user before signing in is guest.
Related
I need to do an url address that looks like website/user/username where username is coming from database. I've tried to reach it by placing a $user variable in my action function as a parameter and result looks like this website/action?user=username. But it looks kind of hinty and ugly. How can I get a desirable result?
First you need to configure url rules in config/web.php.
[
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
"user/<username:\w+>"=> "controller/action"
],
],
],
]
And add url match condition in rules array like
"user/<username:\w+>"=> "controller/action"
Create. htaccess file with below url condition in web folder
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
And generate urls with Url helper class or Html class like below
echo Url::to(['controller/action', 'username' => 'jack']);
Or
echo Html::a('Profile', ['controller/action', 'username' => 'jack'], ['class' => 'profile-link'])
Note:- controller name, action name and username should match with Url condition. Which we define in rules array.
I'm new in Yii2 so I have Brands table with their types ('brand', 'author', 'company') and their slug name so I need the URL like that www.site.com/{brand_type}/{brand_slug} without controller name so how to do that ?
This is commonly called pretty URLs. To do achieve that in Yii2 put this in your app config file under 'components' key
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// ...
'<type:\w+>/slug:\w+>' => 'yourcontroller/youraction',
// ...
],
],
The result is that when you passed a URL in the format you specified, your controller will $type and $slug as parameters you can use in your controller which is expected to take the form:
class YourcontrollerController extends YourBaseController
{
...
public function actionYouraction($type, $slug)
{
// Do whatever you want with these variables
}
...
}
Notice that you will need your web server to configure executing your app's index.php even if it is not in the URL. For Apache this can be done, for example, using .httaccess (More details here) :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
The Definitive Guide to Yii 2.0 has an excellent section about this topic
I've created a module named catalogue with, for the moment, two actions in the default controller:
actionIndex
actionLineProducts
in the index view I have some link which run the line-product's action, the url was the result of:
Url::to(['line-products', 'line' => $line->name])
my goal is to obtain a link like
catalogue/{line-name}
where line-name is the parameter I send to action LineProducts.
My urlManager configurations are:
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<moduls:catalogue>/<controller:default>/<action:line-products>/<line:*>' => '<module>/<line>',
'<controller:\w+>/<id:\d+>' => '<controller>/view/',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
.htaccess configurations:
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
Can anyone explain me why my URL is always like:
http://my-site.dev/catalogue/default/line-products?line={line-name}
You swapped the configuration. The key is the pattern of the url as passed from the browser. The value is the route. Since you are using a specific module, controller and action you can pass those in directly:
'rules' => [
'catalogue/<line>' => 'catalogue/default/line-products'
...
]
You can read the Routing and Url Creation page in the Yii2 guide for more information.
I've got urlManager section in app configuration with several URLs per route:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
'article-a' => 'article/a', // canonic comes first
'article-deprecated-a' => 'article/a',
'article-another-a-is-deprecated' => 'article/a',
'b-annoucement' => 'announcement/b', // canonic comes first
'legacy-b-annoncement' => 'announcement/b',
...
SEF URLs for routes are stored in frontend/config/main.php as an array, with multiple URLs per route. The first URL for the given route (i.e. /article-a) is canonical and the rest are legacy URLs.
What's the most natural way to specify canonical URL for a group of URLs that are pointing to the same route? It can be either rel="canonical" in view or 301/302 redirect to canonical URL.
Canonical URLs should be preferably specified in a place where the routes were defined (frontend/config/main.php configuration file in this case). The requirement here is that canonical URL should be defined outside of the controller, not hard-coded to controller.
I'm not sure how exactly you need to manage your rules so I'll go for a general use case and I'll base my answer on what I did understand from Paddy Moogan's Article which I will resume within the following example and I hope it helps on designing your required solution:
requirement:
Assuming a Search Engine did send a robot to check page B in my website and I'm not fine with people getting to page B instead of page A. So this is how I can clarify my point to the robot:
Forcing a 301 redirect to page A:
Telling the Search Engine that this page is permanently moved to page A. So please don't send more people to it. Send them to page A instead.
Forcing a 302 redirect to page A:
Telling the Search Engine that this page is temporary moved to page A. So do whatever you think it
is appropriate.
Opening page B (200 status code) but insert a Canonical
link element
pointing to page A:
Telling the Search Engine that this page is working fine but it is to me a secondary page and I would suggest sending the next visitors to page
A instead.
design:
So based on that this is how I would see a possible structure to my rules configuration:
'rules' => [
[
// by default: 'class' => 'yii\web\UrlRule',
'pattern' => '/',
'route' => 'site/index',
],
[
// the custom class
'class' => 'app\components\SEOUrlRule',
'pattern' => 'about',
'route' => 'site/about',
'permanents' => [
'deprecated-about',
'an-older-deprecated-about'
],
'temporaries' => [
'under-construction-about',
],
'secondaries' => [
'about-page-2'
]
],
[
// different route with own action but canonical should be injected
'class' => 'app\components\SEOUrlRule',
'pattern' => 'experimental-about',
'route' => 'whatever/experimental',
'canonical' => 'about'
],
]
This way I can chain as much arrays as I need to use Yii's default class yii\web\UrlRule while I can have a custom one in my app components folder dedicated to SEO related controllers.
Before going to code, this is how I would expect my website to behave :
You visit the /about page you get a 200 response (no
canonical added).
You visit the /deprecated-about page you get redirected to
/about with 301 status code.
You visit the /under-construction-about page you get redirected to
/about with 302 status code.
You visit the /about-page-2 page you get a 200 response (rendered by index/about action). No redirections except a similar tag to this is automatically injected into source code:
<link href="http://my-website/about" rel="canonical">
You visit the /experimental-about page you get a 200 response (rendered by its own action whatever/experimental) but with that same canonical tag above injected.
code:
The SEOUrlRule will simply extend \yii\web\UrlRule and override its parseRequest method to define the extra attributes based on which we will force a HTTP redirection or call parent::parseRequest() after registering the canonical link tag to the Yii::$app->view:
namespace app\components;
use Yii;
class SEOUrlRule extends \yii\web\UrlRule
{
public $permanents = [];
public $temporaries = [];
public $secondaries = [];
public $canonical = null;
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
if(in_array($pathInfo, $this->permanents))
{
$request->setPathInfo($this->name);
Yii::$app->response->redirect($this->name, 301);
}
else if(in_array($pathInfo, $this->temporaries))
{
$request->setPathInfo($this->name);
Yii::$app->response->redirect($this->name, 302);
}
else if($this->canonical or in_array($pathInfo, $this->secondaries))
{
$route = $this->name;
if ($this->canonical === null) $request->setPathInfo($route);
else $route = $this->canonical;
Yii::$app->view->registerLinkTag([
'rel' => 'canonical',
'href' => Yii::$app->urlManager->createAbsoluteUrl($route)
]);
}
return parent::parseRequest($manager, $request);
}
}
And that is all what it needs. Note that Yii::$app->controller or its related actions won't be yet available at this early stage of solving routes as it is shown in this lifecycle diagram but it seems that Yii::$app->view is already initialized and you can use its $params property to set custom parameters (as it is done in this example) which may be useful for more advenced cases where more data should be shared or populated to final output.
I think you will have problems when creating the URL from the application to "article/a".
Why not use htaccess or the vhost file to do a 302 redirect to the proper URL?
If you want to handle it through the urlManager, I think you can just register the canonical link
$this->registerLinkTag(['rel' => 'canonical', 'href' => 'article/a']);
in the view.
Mode details here: http://www.yiiframework.com/doc-2.0/yii-helpers-baseurl.html#canonical()-detail
Yii2 provides a tool to generate canonnical urls based on your rules.
\helpers\Url::canonical()
The idea is that it will provide you an url to 'article-a'.
I have the following url structures in my Yii2 application
http://127.0.0.1/frontend/web/index.php?r=site%2Flogin
http://127.0.0.1/frontend/web/index.php?r=site%2Fpage2
http://127.0.0.1/frontend/web/index.php?r=site%2Fsample
http://127.0.0.1/frontend/web/index.php?r=site%2Fsignup
How can I convert that URL to something like
http://127.0.0.1/login.php
http://127.0.0.1/page2.php
http://127.0.0.1/sample.php
http://127.0.0.1/signup.php
I should remove frontend/web/index.php?r=site%2F
I tried like and it didn't work
Options -Multiviews
RewriteEngine On
RewriteBase /
# Force search engines to use http://127.0.0.1/frontend/web/
RewriteCond %{HTTP_HOST} !^http://127\.0\.0\.1/frontend/web/$
RewriteRule ^(.*) http://127.0.0.1/frontend/web/$1 [R=301,L]
# Specify search friendly URLs
RewriteRule ^login\.php$ /index.php?r=site%2Flogin [L]
I also tried like and it didn't work too.
RewriteEngine on
RewriteRule ^frontend/web/index.php?r=site%2F([^\./]+) /$1.php [L]
No need to change .htaccess to achieve this. Adjust urlManager component.
Add this to your application config:
'components' => [
'urlManager' => [
'enablePrettyUrl' => true, // Cancel passing route in get 'r' paramater
'showScriptName' => false, // Remove index.php from url
'suffix' => '.php', // Add suffix to all routes (globally)
],
// Compare requested urls to routes
'rules' => [
'login' => 'site/login',
'page2' => 'site/page2',
'sample' => 'site/sample',
'signup' => 'site/signup',
],
],
As for removing controller part from all other routes - it violates key MVC concepts.
How you define to which controller requested action belongs in that case?
And what in case of actions with the same name?
For example: http://127.0.0.1/create.php - should it load site/create or users/create?
Also I don't sure if it's good practice, but you can write comparisons to all routes the same way with rules, but all action names should be unique.
Conclusion: you can modify urls to desired view as I mentioned above, but omitting controller names is only recommended for default controller (SiteController).
Official documentation:
UrlManager
$enablePrettyUrl
$showScriptName
$suffix
$rules
Routing and URL Creation