3

Everything is working on my localhost, where the .htaccess file is not being used. But when I go to the actual site I am having a problem with AJAX requests. I figured out that the part causing the problem is the removal of the .php extension.

Here is my .htaccess file

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

## redirect to 404 page when file does not exist
ErrorDocument 404 /404.php

## clean urls for blog.php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+blog\.php\?title=([^\s&]+)&? [NC]
RewriteRule ^ /blog/%1? [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^blog/([\w-+]+)/?$ /blog.php?title=$1 [L]

## remove index.php
RewriteCond %{THE_REQUEST} ^.*/index.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L] 
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index$ /$1 [R=301,L]

## To remove .php file extension
## RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
## RewriteRule ^ %1 [R,NC]
## RewriteCond %{REQUEST_FILENAME}.php -f
## RewriteRule ^ %{REQUEST_URI}.php

by commenting out the last four lines it fixed the problem. But I want to be able to remove .php and still use ajax for things like forms.

Here is the ajax

$.ajax({
     type:'post',
     url:'inc/example.php',
     data:$data,
     async:false,
     success:function(){
         console.log('success');
     },
     error:function(r){
         console.log(r.responseText);
     }
});

The error function in the ajax is displaying my 404 error page. I tried removing the .php from the url in the ajax request, no good. Then I tried navigating to inc/example.php and I got the 404 page. The .htaccess file is at the root, and the page making the ajax request is one directory below the root, so the 404 error is happening two directories deep.

1 Answer 1

4

You need to exclude redirecting POST requests. Your ajax code submits to example.php via a POST, and when the rule redirects you to a URL without the php extension, you lose the request body. You should make the condition match only against GET and HEAD requests:

## To remove .php file extension
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\s([^.]+)\.php [NC]
RewriteRule ^ %2 [R,NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.