Question

I am using $this->request->onlyAllow('post', 'delete'); so as to only allow the deletion of records that come from a POST request.

The problem is that I am using URL rewriting in my .htaccess file and it's changing the request from a POST to a GET

This is what my .htaccess file looks like:

<IfModule mod_rewrite.c>
    Options -Indexes
    RewriteEngine On
    RewriteBase /example

    RewriteRule ^homes/$    http://dev.example.com/          [R=301,L]    

    # if this is an existing folder/file then leave
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule . - [L]

    # if no trailing slash then redirect to url with trailing slash
    RewriteRule ^/?(.+)([^/])$ $1$2/ [NE,R=301,L]

    # internal rewrite to controller/dispatcher index.php
    RewriteRule ^.*$ index.php [L,QSA]
</IfModule>

I am using the postLink FormHelper to generate a delete button:

<?php 
    echo $this->Form->postLink(__('Delete'), 
    array('
        controller'=>'posts', 
        'action' => 'delete',), 
    null, 
    __('Are you sure you want to delete "%s?"', $attachment['Post']['name'])); 
?>

The problem is that the action for the form that is generated from the helper does not already have the trailing slash so the htaccess rule steps in and ads this which esentially changes this from a POST method to a GET

Action url that's generated: posts/delete/33579 Action url that's needed: posts/delete/33579/

I have tried adding a slash in the $this->Form->postLink() function however Cake encodes the slash and changes it to a %2F.

I am using CakePHPH 2.3.1

Any suggestions on how to fix this?

Was it helpful?

Solution

This is standard behaviour for a redirect. You have two options:

  • Fixing the url that is generated. This is the most sensible one, as you can probably imagine
  • Preventing the rule from matching if the request is a POST-request (or only let it match with a get request). You can do this with %{THE_REQUEST}

    RewriteCond %{THE_REQUEST} ^GET\ /
    RewriteRule ^(.+)([^/])$ $1$2/ [NE,R=301,L]
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top