简体   繁体   中英

remove .php extension using htaccess from a specific url

I wrote some rules in .htaccess file which are working fine, the rules which I wrote are :

# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\s/+(\S+?)\.php(/\S*)?\sHTTP [NC]
RewriteRule ^ /%1%2 [L,R=301,NE]

# check to see if the request is for a PHP file:
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^/?(.+?)(/.*)?$ /$1.php$2 [L]

Problem: only problem I have with them is that it is removing .php extension from each url as a result my Ajax request are continuously getting 404.

For eg : on a botton an Ajax call is made to url like Ajax/x.php but because of above rule it converted into Ajax/x and return 404.

So now instead of removing .php extension from all files I want to remove .php extension specifically from 2 files ie a.php and b.php .

Need little help with the community, i know I'm almost there.Any help will be appreciated

To remove .php extension from 2 specific files, you can use this :

RewriteCond %{THE_REQUEST} /(a|b)\.php [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [L]
First of all, when you remove the php extension from any url, you have to submit the form by changing removing the .php extension from the action such as
<form class="form-horizontal" method="post" action="new_team" enctype="multipart/form-data">
Same thing also will apply to the ajax file such as
 $.ajax({
            url: 'php/contact_form_submit',
            type: 'post'

.htaccess should look like this
Options +MultiViews
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
# RewriteRule ^([^/]+)/$ http://url/$1 [R=301,L]
RewriteRule ^([^/]+)/$ http://url/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
# RewriteRule ^(.+)\.php$ http://url/$1 [R=301,L]
RewriteRule ^(.+)\.php$ http://url/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]

so try it out and let me know if it solved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM