Andrew Sparrow
Andrew Sparrow

Reputation: 167

Rewrite URL in YII with htaccess

I need to rewrite the following URLS

site.com/events/?event=test

to read like

site.com/events/test

I'm fine with doing this either in htaccess or in the urlManager.

Upvotes: 0

Views: 1092

Answers (3)

Samuel Liew
Samuel Liew

Reputation: 79022

If /events is your controller class, and /test is your parameter for the index action:

class EventController extends Controller {

    public function actionIndex($event) {

Add this rule to your urlManager:

'urlManager' => array(
    'urlFormat' => 'path',
    'rules' => array(
        'event/<event>' => 'event/index',

        ...

This will automatically map test in the url /events/test to the parameter $event in the index action.

    public function actionIndex($event) {

        echo $event; // produces "test"

Upvotes: 1

Howli
Howli

Reputation: 12469

This can be done on htaccess with the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} ^event=([^/]+)$
RewriteRule ^events/$ /events/%1/? [R=302,L]

The above should work (changing R=302 to R=301 when you are sure the redirect works properly).

Upvotes: 0

Jonnny
Jonnny

Reputation: 5039

htaccess should be:

<ifModule mod_rewrite.c>
# Turn on the engine:

RewriteEngine on

# Do not perform redirects for files and directories that exist:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# For everything else, redirect to index.php:

RewriteRule . index.php
</ifModule>

urlmanager should be:

'urlManager'=>array(
        'showScriptName'=>false, // removed index.php with .htaccess
        'urlFormat'=>'path',
        'rules'=>array(
           'test' => 'site/test' // Where controller/view
    ),
),

Upvotes: 0

Related Questions