Bryant Makes Programs
Bryant Makes Programs

Reputation: 1694

Add a htacess redirect to a single Yii2 controller

I have two controllers on a Yii2 PHP site. The first is the SiteController. The second is the BlogController. I have this existing redirect setup.

Options +FollowSymLinks
IndexIgnore */*

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 ^.*$ frontend/web/index.php

This works well, and urls redirect like so:

/site/about redirects to /frontend/web/index.php/site/about

I am now trying to set up behavior to redirect my blog posts.

Currently, the posts are visible at /blog/view?slug=SLUG. I want them to be visible at /blog/SLUG. I want /blog to redirect to /blog/index.

I am terrible at regex and htaccess rewrites. I have tried any number of derivatives and I can not get the urls to redirect correctly.

/blog/test should redirect to /frontend/web/index.php/blog/view?slug=test and /blog/ or /blog should redirect to /frontend/web/index.php/blog/index.

Could anyone help? My latest (failing) attempt is:

Options +FollowSymLinks
IndexIgnore */*

RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^blog/(.*)$ frontend/web/index.php/blog/view?slug=%1

# otherwise forward it to index.php
RewriteRule ^.*$ frontend/web/index.php

If anyone with Yii2 experience would like to chime in, I may actually be misunderstanding my current redirect as well.

Upvotes: 1

Views: 251

Answers (1)

SHIKHAR SINGH
SHIKHAR SINGH

Reputation: 439

Why don't you use rules in Yii2 itself.They can be set in config prettyURL like

       'urlManager' => [
    'showScriptName' => false,
    'enablePrettyUrl' => true,
    'rules' => array(
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' =>          '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    ),
]

],

This would be better than changing your htaccess file because if Yii2 has a feature then why not use it? Hope I got your doubt cleared if not then please let me know.

Upvotes: 1

Related Questions