cakephp rewrite url not working

3.1k views Asked by At

I have the CakePHP simple program ( CakePHP: version 2.1.3, Centos 6.x and Apache: 2.2.15).

Now I want to change url from: http://domain.com/frontend/login

to new url like: http://domain.com/user-login.html

I want to use new URL, and remove old URL.

I tried to rewrite ( by config .htaccess with mod rewrite, I configed /etc/httpd/conf/httpd.conf already: Change AllowOverride None to AllowOverride All).

and some .htaccess files like belows:

/root/.htaccess

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
   #rewrite to new url
   RewriteRule ^frontend/login$  user-login.html [L]
 </IfModule>

/root/app/.htaccess

 <IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$    webroot/    [L]
   RewriteRule    (.*) webroot/$1    [L]
 </IfModule>

and /root/app/webroot/.htaccess

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

But my new url http://domain.com/user-login.html is not work.

There is any thing wrong in my config?

1

There are 1 answers

1
Mike Rockétt On

You should not be doing this with .htaccess. If you do, CakePHP will not understand the request.

Instead, you need to connect a route to a controller in CakePHP itself. In essence, you are creating an alias URI for the controller method in question. The documentation for routing is available here:

http://book.cakephp.org/2.0/en/development/routing.html

Essentially, you need to open up app/Config/routes.php, and enter the following:

Router::connect(
    '/user-login.html',
    array('controller' => 'frontend', 'action' => 'login')
);

(Assuming your controller is called frontend.)

If that does not work, then you may need to tell CakePHP to parse and strip out the extension first:

Router::parseExtensions('html');

And then route like this instead:

Router::connect(
    '/user-login',
    array('controller' => 'frontend', 'action' => 'login')
);

Note: I have not tested this. The above is simply based on what is described in the documentation.


Update: Redirect from old URIs

Now that the application understands the routes you want to use, you can create redirects in your first .htaccess file:

RewriteEngine On
RewriteRule ^frontend/login$ /user-login.html [R=302,L]
# ... etc ...

Alternatively, you can use the Router::redirect() in your route configuration:

Router::redirect('/frontend/login', '/user-login.html', array('status' => 302));

(To make that redirect permanent and cached by browsers and search engines, change 302 to 301.)